BufferedReader in Java is skipping the last empty line in file - java

I have a file in following format:
Name: John
Text: Hello
--empty line-- Buffered Reader is reading this.
Name: Adam
Text: Hi
--empty line-- Buffered Reader is skipping this line.
I tried multiple ways to read the last empty line but its not working. Any suggestions?
I have a program which validates that the message is in correct format or not.
For the correct format there should be three lines first with name followed by text and empty line.
As the last empty line is not read by the BufferedReader, my program always says that the message is in wrong format.
Sample Code I am using:
File file = new File(absolutePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
process(line);
}

The code is working the way it is supposed to. The last (empty) line is the end of file (EOF). A valid line is terminated by a carriage return and line feed. Line #3 is read because of this. I included an image of your file showing the text and symbols (used Notepad++ for this)
If I add another blank line at the end, notice how the previous blank line is now terminated.
I modified your code slightly to run this scenario
public static void main (String[] args) throws IOException {
File file = new File("emptyline.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
int linenum = 1;
while ( (line = br.readLine()) != null) {
System.out.println("Line " + (linenum++) + ": " + line);
}
br.close();
}
When I run the code with two blank lines at the end, this is the result:
Line 1: Name: John
Line 2: Text: Hello
Line 3:
Line 4: Name: Adam
Line 5: Text: Hi
Line 6:
If you have software that validates this file based on data being structured this way, I am not sure what to say. That seems a bad way to validate a file. There are more effective ways to do this, like using checksum. Maybe if you try with two empty lines at the end, the validator will accept it as a correct format.

Related

How to read every line of a text file including empty lines

I want to be able to read an entire text file that has empty lines between text. Every solution I try to implement seems to stop reading after it reaches an empty line. I want to be able to read an entire text file, including empty lines, and store the contents in a String. This is what I have now. I included two implementations. How can I alter either of the implementations to continue reading after an empty line? Also, I want the empty lines in the text file to be included in the String that it is being stored in.
File templateFile = new File(templatePath);
String oldContent = "";
BufferedReader reader = new BufferedReader(new FileReader(templateFile));
//Implementation 1
String line = reader.readLine();
while(line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
/* Implementation 2
Scanner sc = new Scanner(templateFile);
while(sc.hasNext()) {
oldContent = sc.nextLine();
} */
Using java 11 java.nio.file.Files.readString()
oldContent = Files.readString(Paths.get(templatePath));

Need to tokenize a file containing one line only

I need to open a file test.txt this file only has one sentence, but it is all in one line only. My job is to separate each word and display all the words that are misspelled.
I've tried using a BufferReader and FileReader, but it just prints out the name of the file. I want it to see the first line and essentially put all the words in an array. If anyone can explain how exactly I should be using BufferReader or FileReader would be great.
This is test.txt:
The warst drought in the United States in neearly a century is expected to drive up the price of milk, beef and pork next yeer, the government said Wednesdaay, as consumers bear some of the bruntt of the sweltering heat that is drivng up the cost of feed corrn.
Note: This appears as one single line in the editor.
This is what I tried:
FileReader fr = new FileReader("test.txt");
BufferReader br = new BufferReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null){
sb.append(s);
sb.toString();
}
Thanks for your help.
for (String line : Files.readAllLines(Paths.get("filepath.txt"))) {
// ...
}
Java: How to read a text file

Counting Words and Newlines In A File Using Java?

I am writing a small java app which will scan a text file for any instances of particular word and need to have a feature whereby it can report that an instance of the word was found to be the 14th word in the file, on the third line, for example.
For this i tried to use the following code which i thought would check to see whether or not the input was a newline (\n) character and then incerement a line variable that i created:
FileInputStream fileStream = new FileInputStream("src/file.txt");
DataInputStream dataStream = new DataInputStream(fileStream);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(dataStream));
String strLine;
String Sysnewline = System.getProperty("line.separator");
CharSequence newLines = Sysnewline;
int lines = 1;
while ((strLine = buffRead.readLine()) != null)
{
if(strLine.contains(newLines))
{
System.out.println("Line Found");
lines++;
}
}
System.out.println("Total Number Of Lines In File: " + lines);
This does not work for, it simply display 0 at the end of this file. I know the data is being placed into strLine during the while loop as if i change the code slightly to output the line, it is successfully getting each line from the file.
Would anyone happen to know the reason why the above code does not work?
Read the javadocs for readLine.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
readLine() strips newlines. Just increment every iteration of the loop. Also, you're overcomplicating your file reading code. Just do new BufferedReader(new FileReader("src/file.txt"))

how to search for a certain word in a text file in java

how to search for a certain word in a text file in java?
Using buffered reader, I have this code, but I get a
java.lang.ArrayIndexOutOfBoundsException
Please help me determine what's wrong with my program.
System.out.println("Input name: ");
String tmp_name=input.nextLine();
try{
FileReader fr;
fr = new FileReader (new File("F:\\names.txt"));
BufferedReader br = new BufferedReader (fr);
String s;
while ((s = br.readLine()) != null) {
String[] st = s.split(" ");
String idfromtextfile=st[0];
String nemfromtextfile = st[1];
String scorefromtextfile=st[2];
if(nemfromtextfile.equals(tmp_name)){
System.out.println("found");
}else{
System.out.println("not found");
}
}
}catch(Exception e){ System.out.println(e);}
names.txt looks like this:
1
a
0
2
b
0
Your code expects each line in the file to have three space-separated words. So your file must look like this:
1 a 0
2 b 0
The ArrayIndexOutOfBoundsException occurs if there is a line in the file that does not have three space-separated words. For example, there might be an empty line in your file.
You could check this in your code like this:
if ( st.length != 3) {
System.err.println("The line \"" + s + "\" does not have three space-separated words.");
}
You can use the Pattern/Matcher combination described here, or try the Scanner. Use the Buffered reader like this :
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
and extract the string with in.toString()
If text is huge and you don't want to read it at once and keep in memory. You may constantly read a line with readLine(), and search each of the output line for a pattern.
Here is an example of how to do it using BufferedReader
link text

Java - Reading a csv file line by line - stuck with weird non-existent characters being read!

hello fellow java developers. I'm having a very strange issue.
I'm trying to read a csv file line by line. Im at the point where Im just testing out the reading of the lines. ONly each time that I read a line, the line contains square characters between each character of text. I even saved the file as a txt file in wordpad and notepad with no change.
Thus I must be doing something stupid...
I have a csv file, standard csv file, yes a text file with commas in it. I try to read a line of text, but the text is all f-ed up and cannot find the phrase within the text.
Any advice? code below.
//open csv
File filReadMe = new File(strRoot + "data2.csv");
BufferedReader brReadMe = new BufferedReader
(new InputStreamReader(new FileInputStream(filReadMe)));
String strLine = brReadMe.readLine();
//for all lines
while (strLine != null){
//if line contains "(see also"
if (strLine.toLowerCase().contains("(see also")){
//write line from "(see also" to ")"
int iBegin = strLine.toLowerCase().indexOf("(see also");
String strTemp = strLine.substring(iBegin);
int iLittleEnd = strTemp.indexOf(")");
System.out.println(strLine.substring(iBegin, iBegin + iLittleEnd));
}
//update line
strLine = brReadMe.readLine();
} //end for
brReadMe.close();
I can only think that this is an inconsistent character encoding. Open the file in notepad, choose Save As, and select UTF-8 in the drop down for "encoding". Then add "UTF-8" as a second parameter to InputStreamReader, e.g.
BufferedReader brReadMe = new BufferedReader
(new InputStreamReader(new FileInputStream(filReadMe), "UTF-8"));
That should sort out any inconsistencies with encoding.

Categories

Resources