I am designing a Utility that counts the words and Number of newline characters.
I have done count task but i dont know how to count number of new line charcaters in file.
Code:
System.out.println ("Counting Words");
InputStream stream = Run.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
BufferedReader br = new BufferedReader (r);
String line = br.readLine();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts){
count++;
}
line = br.readLine();
}
System.out.println(count);
test
This is simple file reading by Java Program
Just look inside the words:
for (char c : w.toCharArray()) {
if (c == '\n') {
numNewLineChars++;
}
}
Which goes inside the for loop you already have.
System.out.println ("Counting Words");
InputStream stream = Run.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
BufferedReader br = new BufferedReader (r);
String line = br.readLine();
int word_count = 0;
int line_count = 0;
while (line != null) {
String[] parts = line.split(" ");
word_count += parts.length;
line_count++;
line = br.readLine();
}
System.out.println("Word count: " + word_count + " Line count: " + line_count);
It maybe a better option here to use the LineNumberReader class for counting and reading the lines of text. Although this isn't the most efficient way for counting lines in a file (according to this question) it should suffice for most applications.
From LineNumberReader for readLine method:
Read a line of text. Whenever a line terminator is read the current line number is incremented. (A line terminator is usually a newline character '\n' or a carriage return '\r').
This means that when you call the getLineNumber method of the LineNumberReader class, it will return the current line number that has been incremented by the readLine method.
I have included comments in the code below explaining it.
System.out.println ("Counting ...");
InputStream stream = ParseTextFile.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
/*
* using a LineNumberReader allows you to get the current
* line number once the end of the file has been reached,
* without having to increment your original 'count' variable.
*/
LineNumberReader br = new LineNumberReader(r);
String line = br.readLine();
// use a long in case you use a large text file
long wordCount = 0;
while (line != null) {
String[] parts = line.split(" ");
wordCount+= parts.length;
line = br.readLine();
}
/* get the current line number; will be the last line
* due to the above loop going to the end of the file.
*/
int lineCount = br.getLineNumber();
System.out.println("words: " + wordCount + " lines: " + lineCount);
Related
Sorry for the noob question, but I feel like my code is correct but I can't see why the read won't go to the next line:
This is my code so far:
BufferedReader buffer = null;
try {
FileReader file = new FileReader(filename);
buffer = new BufferedReader(file);
String line = buffer.readLine();
String[] separations = line.split(", ");
System.out.println(separations[0]);
while(line!= null) {
this.times.add(separations[0]);
Double number = Double.parseDouble(separations[1]);
allNumbers.add(number);
line = buffer.readLine();
}
The issue was not that the buffer was only reading one line but I was tokenizing the line outside of the loop, so the same information got stored for x number of lines:
Solution:
while (line != null) {
String[] separations = line.split(", "); // this should be inside the loop
if (separations.length > 1) {
this.times.add(separations[0]);
Double number = Double.parseDouble(separations[1]);
allNumbers.add(number);
}
line = buffer.readLine();
}
I have a text file like this:
Emma,F,20355
Olivia,F,19553
Sophia,F,17327
Ava,F,16286
Isabella,F,15504
Mia,F,14820
Abigail,F,12311
Emily,F,11727
I am trying to remove words after , and also put two lines in one line for every two lines.
For example:
Emma Olivia
Sophia Ava
Isabella Mia
Abigail Emily
The program can do the first part, but I don't know how the program can do the second part. I can split the words and numbers after first ,, but I got stuck how I can can arrange lines.
Here is the code:
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String[] a;
String res;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
res = a[0] + "\n";
writer.write(res);
}
writer.close();
reader.close();
I think I need to create a for loop inside while loop, but I am not sure what to write to count even or odd lines.
Change to to something like this :
int count = 1;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
res = a[0] + count % 2 == 0 ? "\n" : " ";
count++;
writer.write(res);
}
try (
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))
) {
while (true) {
String line1 = reader.readLine();
if (line1 == null) {
break;
}
writer.write(line1.split(",", 2)[0]);
String line2 = reader.readLine();
if (line2 == null) {
writer.newLine();
break;
}
writer.write(" " + line2.split(",", 2)[0]);
writer.newLine();
}
}
int newLine = 1;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
if (newLine % 2 == 0)
res += a[0] + "\n";
else
res += a[0] + " ";
newLine++;
}
writer.write(res);
Try reading two lines in at the same time if there is a second line left in the reader.
Something like this:
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String[] a;
String[] b;
String res;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
if (reader.hasNext()) {
b = reader.readLine().split(",");
res = a[0] + " " + b[0] + "\n";
} else {
res = a[0]+"\n";
}
writer.write(res);
}
writer.close();
reader.close();
As mentioned above, read in two lines at a time. Combine them, then split based on the delimiter (comma) - Should then be easy to write out new format to a text file (Maybe pop the results in a list, then iterate over the list to write it out.
This is not a complete solution, but should be enough for you to get the idea.
// Read two lines at a time
String currentLine = reader.readLine(); //Emma,F,20355
String nextLine = reader.readLine(); //Olivia,F,19553
String combinedLine = currentLine + "," + nextLine;
// split into separate elements
String[] elements = combinedLine.split(",");
List<String> newLines = new ArrayList<>();
newLines.add(elements[0] + " " + elements[3]);
for (final String line : newLines) {
// write to file
writer.write(res);
}
I am trying to create a program in Java that reads from a file, extracts the first digit of every number, determines the frequencies of 0-9, and prints out the frequencies (in percentages) of the numbers 0 through 9. I already figured out how to read from my file ("lakes.txt");
FileReader fr = new FileReader ("lakes.txt");
BufferedReader br = new BufferedReader(fr);
//for loop that traverses each line of the file
int count = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
System.out.println(s); //print out every term
count++;
}
String [] nums;
nums = new String[count];
//close and reset file readers
fr.close();
fr = new FileReader ("lakes.txt");
br = new BufferedReader(fr);
//read each line of the file
count = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
nums[count] = s;
count++;
}
I am currently printing out every term just to make sure it is working.
Now I am trying to figure out how to extract the first digit from each term in my string array.
For example, the first number in the array is 15,917, and I want to extract 1. The second number is 8,090 and I want to extract 8.
How can I do this?
To extract the first number from a String
Get the first letter from the String
Parse (1) into a number
For example:
String firstLetter = Character.toString(s.charAt(0));//alternatively use s.substring(0,1)
int value = Integer.parseInt(firstLetter);
This would be placed inside the file reading loop, assuming each line of the file contains a numeric value (in other words, no further processing or error handling of the lines of the file is required).
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TermReader {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader ("lakes.txt");
BufferedReader br = new BufferedReader(fr);
int[] tally = new int[]{0,0,0,0,0,0,0,0,0,0};
int total = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
char[] digits = s.toCharArray();
for(char digit : digits) {
if( Character.isDigit(digit)) {
total++;
tally[Integer.parseInt(Character.toString(digit))]++;
break;
}
}
}
br.close();
for(int index = 0; index < 10; index++) {
double average = tally[index] == 0 ? 0.0 : (((double)tally[index]) / total) * 100;
System.out.println("[" + index + "][" + tally[index] + "][" + total + "][" + Math.round(average * 100.0) / 100.0 + "]");
}
}
}
I am taking a command line input string like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
I want to split this string which is:
String line = "int t; //variable t
t->a = 0; //t->a does something
return 0;"
like this:
String[] arr = line.split("\n");
arr[0] = "int t; //variable t";
arr[1] = "t->a=0; //t->a does something";
arr[2] = "return 0";
but when i run my java program that split function only returns this:
arr[0] = "int t; //variable t";
it didn't returns other two strings that i mentioned above,why this is happening please explain.
The method readLine() will read the input until a new-line character is entered. That new-line character is "\n". Therefore, it won't ever read the String separated by "\n".
One solution:
You can read the lines with a while loop and store them in an ArrayList:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
for (String s : lines) {
System.out.println(s);
}
To stop the while you will have to press Ctrl + z (or Ctrl + d in UNIX, if I'm not wrong).
From your comment you seem to take the input like this
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
Here the line represents already split string by \n. When you hit enter on the console, the text entered in one line gets captured into line. As per me you are reading line, only once which captures just int t;//variable t, where there is nothing to split.
This should work!Also make sure if your input contains \n
String[] arr = line.split("\r?\n")
I have files containing text in pattern like this
Type:status
Origin:some text
Text:some text
URL:some url
Time:time
around 500 lines with same pattern. I want to extract only the text part from it. I tried reading the file with BufferedReader and used indexOf("Text") and indexOf("URL") and subString(i,j) but its giving exception at run time. How can I do this. My code:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
str= str + s;
i = str.indexOf("Text:");
j= str.indexOf("URL:");
String a= str.substring(i, j);
bw.write(a);
}
br.close();
bw.close();
The "Text:" is found first in the 3rd line and "URL:" in the 4th, but if your program doesn't find both strings, it throws an exception.
Even if it worked you would find the same text over and over again.
Try something like this:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
String s;
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
if (s.startsWith("Text:"))
bw.write(s);
}
br.close();
bw.close();
You could use
String[] pieces = str.split(":");
That will give you an array of strings split by what ever you put in the parenthesis. Then if you know the pattern you can get each piece out by iterating through it in a loop. For example: if you know that Type is at [0] and six things in each sequence you can say that the next Type will be at [6] and so on.
You should check for indexes. Of i and j. If one line is wrong, it will skip it and print the line that is wrong to the console. You should probably handle it in a different way but keep in mind that substring shouldn't love indexes of -1.
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String tokenText = "Text:";
String tokenURL = "URL:";
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
String a;
str = str + s;
i = str.indexOf(tokenText);
j = str.indexOf(tokenURL);
if (i < 0 && j >= 0){
// pad with the token string
a = s.substring(j + tokenURL.length);
} else if(i >= 0) {
// pad with the token string
a = s.substring(i + tokenText.length);
} else {
System.out.printl("Unparsed line:");
System.out.printl(s);
}
bw.write(a);
}
br.close();
bw.close();
That said, as jonhchen902 said in the comments, you could also check for the strings after the while loop. It really depends on your input file and if you're expecting to find the "string" multiple times or once.
According to your example, Text: and Url: are on consecutive lines.
Your problem is you're reading the file line by line (br.readLine()), so calling indexOf() will most of the time return -1 in i or j (and you will never find both strings, since they aren't on the same line).
As the javadoc of substring() states, calling the method with a negative start index will throw an IndexOutOfBoundsException. So your approach isn't right.
You should instead parse the file line by line as you're doing, and simply test for a positive index to the call to indexOf("Text:"), and then substring the current line starting at the returned index + 5.
Not tested:
while ((line = br.readLine()) != null) {
i = line.indexOf("Text:");
if (i > 0) {
String text = line.substring(i);
bw.write(text + "\n");
}
}