jackie chen jackie chen - 15 days ago 5x
Java Question

File reader in eclipes

Can anyone tell me why my code never reads the 2nd line of my file? if my 2nd line in the file (for example .txt file) start at a new line and indent that line, it will not read it.But if it is in a new line and it isn't indented , it will read. also it reads 3rd line fine. Is it something with the while loop ?

Scanner keyboard = new Scanner (System.in);
System.out.println("Input the file name");

String fileName = keyboard.nextLine();
File input = new File (fileName);
BufferedReader reader = new BufferedReader(new FileReader(input));
String content = reader.readLine();
while (reader.readLine() != null)
content = content + reader.readLine();



Each time you call readLine() it reads the next line. The statement

while (reader.readLine() != null)

reads a line but does not do anything with it. What you want is

String line;
StringBuilder buf;
while ( (line = reader.readLine()) != null)
content = buf.toString();

Using a StringBuilder is much better as it avoids reallocating and copying the entire string each time you append.