How to remove commas from a text file? - java

I got this far, but it seems that buffer won't take arrays, because first I had it this way
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
// System.out.println (strLine);
String Record = strLine;
String delims = "[,]";
String[] LineItem = Record.split(delims);
//for (int i = 0; i < LineItem.length; i++)
for (int i = 0; i == 7; i++)
{
System.out.print(LineItem[i]);
}
now I leave at this, because it's reading but not taking out commas.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class mainPro1test {
public static void main(String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\2010_Transactions.txt"));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
String Record = text;
String delims = "[,]";
String[] LineItem = Record.split(delims);
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
of how it should look like
input
Sell,400,IWM ,7/6/2010,62.481125,24988.02,4.43
Sell,400,IWM ,7/6/2010,62.51,24999.57,4.43
output
Sell 400 IWM 7/6/2010 62.481125 24988.02 4.43
Sell 400 IWM 7/6/2010 62.51 24999.57 4.43

If you only want to remove commas from a String, you can use String.replaceAll(",","");
If you want to replace them by spaces, use String.replaceAll(","," "):
while ((text = reader.readLine()) != null) {
contents.append(text.replaceAll(","," ");
}
Also in your code you seem to split the input, but don't use the result of this operation.

Easier is to define a new InputStream that just removes the commas...
class CommaRemovingStream extends InputStream {
private final InputStream underlyingStream;
// Constructor
#Override public int read() throws IOException {
int next;
while (true) {
next = underlyingStream.read();
if (next != ',') {
return next;
}
}
}
}
Now you can read the file without commas:
InputStream noCommasStream = new CommaRemovingStream(new FileInputStream(file));

Related

Read, and then split a text file into different arrays

So I'm trying to use a BufferedReader to split a text file into 2 different arrays, I've written some code but I'm not sure where to go from here.
I know how to populate an array, but i just cant seem to get the specific lines.
So, one array for NEW_OFFICE containing only the numbers, and one for MAIN_ADDRESS containing only the numbers below it.
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("myDelivery.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String words = read.split("NEW_OFFICE")[0];
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception ignored) { }
}
This is the text file:
NEW_OFFICE
-92.48392883 52.96531732
-2.483984994 92.48392883
MAIN_ADDRESS
-1.207614869 52.98908196
NEW_OFFICE always is the first line, and always has two lines below
it, the same goes for MAIN_ADDRESS it always has one line below it.
NEW_OFFICE & MAIN_ADDRESS can't appear more than once.
Based on your comment mentioned above, given below is the solution:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
String[][] office = new String[2][2];
String[][] main = new String[1][2];
try (BufferedReader in = new BufferedReader(new FileReader("myDelivery.txt"))) {
String read;
while ((read = in.readLine()) != null) {
if (read.equalsIgnoreCase("NEW_OFFICE")) {
// Read next two lines
for (int i = 0; i < 2; i++) {
if ((read = in.readLine()) != null) {
office[i] = read.split("\\s+");
}
}
} else if (read.equalsIgnoreCase("MAIN_ADDRESS")) {
// Read next line
if ((read = in.readLine()) != null) {
main[0] = read.split("\\s+");
}
}
}
}
// Display office[][]
System.out.println("Displaying office:");
for (String[] officeData : office) {
System.out.println(Arrays.toString(officeData));
}
// Display main[][]
System.out.println("Displaying main:");
for (String[] mainData : main) {
System.out.println(Arrays.toString(mainData));
}
}
}
Output:
Displaying office:
[-92.48392883, 52.96531732]
[-2.483984994, 92.48392883]
Displaying main:
[-1.207614869, 52.98908196]
Notes:
\\s+ is for splitting the line on space(s).
Use try-with-resources syntax to simplify your code.
.split() does take a string, but it should be a regex, not the substring that you want to split it on. You want to change your code like this:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String read;
String office = "";
while ((read = in.readLine()) != null) {
if (read.contains("NEW_OFFICE")) {
office = "NEW_OFFICE";
} else if (read.contains("MAIN_ADDRESS")) {
office = "MAIN_ADDRESS";
} else {
System.out.println(office + " : " + read);
}
}
} catch (IOException e) {
e.printStackTrace();
}
I have also changed your try with try-with-resources so you don't have to worry about closing the resource.
I´d go with somethin like this.
Please be aware that I don´t have an IDE right now so this is basically pseudo code:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String line = null;
boolean isOffice = false;
ArrayList<double> officeInts = new ArrayList<double>();
ArrayList<double> addressInts = new ArrayList<double>();
while ((line = in.readLine()) != null) {
if (line.contains("NEW_OFFICE")) {
isOffice = true;
continue;
} else if (line.contains("MAIN_ADDRESS")) {
isOffice = false;
continue;
}
for(String s : line.split(" "){
double num = Double.parseDouble(s);
if(isOffice) {
officeInts.add(num);
} else {
addressInts.add(num);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}

How to print and remove integers from a file on computer

I am trying to read a file from my computer, and have the system print out the file only containing the letters, and not printing the numbers. I have other functions in my code already so please look near the bottom where I am stuck with arraylist. How do I ignore the integers when printing?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("/Users/wolftrek/Downloads/example.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
myFileLines.add(sCurrentLine);
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
for (int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains("example word")) {
System.out.println(myFileLines.get(i));
}
}
Scanner myScanner = new Scanner (System.in);
String enteredString = "";
System.out.println("Please enter the characters to search for: ");
enteredString = myScanner.nextLine();
for(int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains(enteredString)) {
System.out.println(myFileLines.get(i));
}
}
ArrayList<String> input = myFileLines;
String extract = input.replaceAll("[^a-zA-Z]+", "");
System.out.println(extract);
}
}
The error is you are applying replaceAll on a list and also the regex is not correct. Something like below will do the job. I am not clear if that's what you want though.
ArrayList<String> input = myFileLines;
for (String e : input) {
String extract = e.replaceAll("\\d+", "");
System.out.println(extract);
}

Why is there no output when I run my code?

I am trying to read a file called ecoli.txt, which contains the DNA sequence for ecoli, and store its contents into a string. I tried to print the string to test my code. However, when I run the program, there is no output. I am still new to java so I am sure there is an error in my code, I just need help finding it.
package codons;
import java.io.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader codons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_string = new StringBuilder();
String line = ecoli.readLine();
while(line != null);
{
dna_string.append(line);
line = ecoli.readLine();
}
String string = new String(dna_string);
System.out.println(string);
ecoli.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
edit:
I was still having trouble getting the program to work the way I wanted it to so I attempted to complete writing the rest of what I wanted in the program and I am still not getting any output. Anyway, this is where I am at now:
package codons;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader filecodons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_sb = new StringBuilder();
String line = ecoli.readLine();
while(line != null)
{
dna_sb.append(line);
line = ecoli.readLine();
}
String dna_string = new String(dna_sb);
ecoli.close();
BufferedReader codons = new BufferedReader(filecodons);
StringBuilder codon_sb = new StringBuilder();
String codon = codons.readLine();
while(codon != null)
{
codon_sb.append(codon);
line = codons.readLine();
}
String codon_string = new String(codon_sb);
codons.close();
for(int x = 0; x <= codon_sb.length(); x++)
{
int count = 0;
String codon_ss = new String(codon_string.substring(x, x+3));
for(int i = 0; i <= dna_sb.length(); i++)
{
String dna_ss = new String(dna_string.substring(i, i+3));
int result = codon_ss.compareTo(dna_ss);
if(result == 0)
{
count += 1;
}
}
System.out.print("The codon '");
System.out.print(codon_ss);
System.out.print("'is in the dna sequence");
System.out.print(count);
System.out.println("times.");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Remove the ; after while(line != null), it causes an infinite loop instead of executing the next instructions.
The reason is explained here: Effect of semicolon after 'for' loop (the question is about the C language, but it is equivalent in Java).

Java StringTokenizer only reading first line

My problem is that StringTokenizer seems to only read the first line of ip.txt
What I'm trying to do is load a list of IP addresses from "ip.txt" and save it into an array to automatically ping devices on my network to see if their online. No matter what I try I can't get more than the first line in "ip.txt" into the array. My delimiter is "//" and the name of the ip address is also stored in the txt file. I included the code and a sample of the text file.
Thanks in advance!!
public class IP {
public static IP[] ips = new IP[100];
public static int total_ips=0;
String name;
String ip1;
String ip2;
String ip3;
String ip4;
String fullIP;
public static void read_ips() throws FileNotFoundException{
FileInputStream fstream1 = new FileInputStream("ip.txt");
String line;
String delimiter = "//";
StringTokenizer tokenizer;
BufferedReader input = null;
try {
int i = 0;
int totalIps = 0;
input = new BufferedReader(new InputStreamReader(fstream1));
line = input.readLine();
//outer while
while(line != null) {
tokenizer = new StringTokenizer(line, delimiter);
while(tokenizer.hasMoreElements()) {//process tokens in line
ips[i] = new IP();
ips[i].name = tokenizer.nextToken();
ips[i].ip1 = tokenizer.nextToken();
ips[i].ip2 = tokenizer.nextToken();
ips[i].ip3 = tokenizer.nextToken();
ips[i].ip4 = tokenizer.nextToken();
ips[i].fullIP = ips[i].ip1+"."+ips[i].ip2+"."+ips[i].ip3+"."+ips[i].ip4;
i++;
totalIps = i;
System.out.println(line);
}
line = input.readLine(); //next line
}//close outer while
total_ips = totalIps; // count of total cars
System.out.println("total_ips after i++ "+total_ips);
}catch (FileNotFoundException e) {
System.out.println("Unable to open file " + fstream1);
} catch (IOException e) {
System.out.println("Unable to read from file " + fstream1);
}finally {
// Close the file
try {
if (input != null)
input.close();
} catch (IOException e) {
System.out.println("Unable to close file " + fstream1);
}
}
}
}
And here is an example of ip.txt
Desktop1//192//168//1//127//
Desktop2//192//168//1//128//
Desktop3//192//168//1//129//
Your code should be working fine. The more classic approach to iterate over the BufferedReader one line at a time is by using an expression like:
while ( (line = input.readLine()) != null) {.
That's about the only refactoring I did to your code and it is working. You may want to print the fullIP in order to check that you are correctly retrieving it.
Here is the code:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class IP {
public static IP[] ips = new IP[100];
public static int total_ips=0;
String name;
String ip1;
String ip2;
String ip3;
String ip4;
String fullIP;
public static void main(String[] args) throws IOException {
read_ips();
}
public static void read_ips() throws FileNotFoundException{
FileInputStream fstream1 = new FileInputStream("c:\\ips\\ip.txt");
String line;
String delimiter = "//";
StringTokenizer tokenizer;
BufferedReader input = null;
try {
int i = 0;
int totalIps = 0;
input = new BufferedReader(new InputStreamReader(fstream1));
while ( (line = input.readLine()) != null) {
tokenizer = new StringTokenizer(line, delimiter);
while(tokenizer.hasMoreElements()) {//process tokens in line
ips[i] = new IP();
ips[i].name = tokenizer.nextToken();
ips[i].ip1 = tokenizer.nextToken();
ips[i].ip2 = tokenizer.nextToken();
ips[i].ip3 = tokenizer.nextToken();
ips[i].ip4 = tokenizer.nextToken();
ips[i].fullIP = ips[i].ip1+"."+ips[i].ip2+"."+ips[i].ip3+"."+ips[i].ip4;
System.out.println(ips[i].fullIP);
i++;
totalIps = i;
System.out.println(line);
}
}
total_ips = totalIps; // count of total cars
System.out.println("total_ips after i++ "+total_ips);
}catch (FileNotFoundException e) {
System.out.println("Unable to open file " + fstream1);
} catch (IOException e) {
System.out.println("Unable to read from file " + fstream1);
}finally {
// Close the file
try {
if (input != null)
input.close();
} catch (IOException e) {
System.out.println("Unable to close file " + fstream1);
}
}
}
}
And an illustration:

I am trying to count characters from a within file

What I am trying to do here is read a file and count each character. Each character should add +1 to the "int count" and then print out the value of "int count".
I hope that what I am trying to do is clear.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
int count = 0;
Scanner scan = null;
Scanner cCount = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("greeting")));
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
finally {
if (scan != null) {
scan.close();
}
}
try {
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext("")) {
count++;
}
}
finally {
if (cCount != null) {
scan.close();
}
}
System.out.println(count);
}
}
Add a catch block to check for exception
Remove the parameter from hasNext("")
Move to the next token
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext()) {
count = count + (cCount.next()).length();
}
Using java 8 Stream API, you can do it as follow
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountCharacter {
private static int count=0;
public static void main(String[] args) throws IOException {
Path path = Paths.get("greeting");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
count = lines.collect(Collectors.summingInt(String::length));
}
System.out.println("The number of charachters is "+count);
}
}
Well if your looking for a way to count only all chars and integers without any blank spaces and things like 'tab', 'enter' etc.. then you could first remove those empty spaces using this function:
st.replaceAll("\\s+","")
and then you would just do a string count
String str = "a string";
int length = str.length( );
First of all, why would you use try { } without catch(Exception e)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
text += line;
}
int c = 0; //count of any character except whitespaces
// or you can use what #Alex wrote
// c = text.replaceAll("\\s+", "").length();
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
c++;
}
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
System.out.println("File Not Found");
} finally {
if (reader != null) { reader.close();
}
}

Categories