Search code examples
javastringeclipsebufferedreaderfilereader

File reader in eclipse


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();
content.replaceAll("\\s+","");
while (reader.readLine() != null) {
    content = content + reader.readLine();
}

System.out.println(content);

Solution

  • See my comments in the code below.

    String content = reader.readLine();          //here you read a line
    content.replaceAll("\\s+","");
    while (reader.readLine() != null)            //here you read a line (once per loop iteration)
    {
        content = content + reader.readLine();   //here you read a line (once per loop iteration)
    }
    

    As you can see, you are reading the second line in the beginning of your while loop, and you are checking if it is equal to null before moving on. However, you do nothing with that value, and it is lost. A better solution would look like this:

    String content = ""
    String input = reader.readLine(); 
    while (input != null)            
    {
        content = content + input;   
        input = reader.readLine();
    }
    

    This avoids the problem of reading and then throwing away every other line by storing the line in a variable and checking the variable for null instead.