-1

I am trying to read the content of a textfile in Java using BufferedReader. However, only the first line is being retrieved.

Here's the code:

public String myFile(String file)
{
    String dataInTextFile = "";
    try 
    {
        BufferedReader fileInput = new BufferedReader(new FileReader(file));

        try 
        {
            dataInTextFile = fileInput.readLine();
        } 
        catch (IOException e) 
        {
            System.out.println(e);
        }
    } 

    catch (FileNotFoundException e) 
    {
        System.out.println(e);
    }

    return dataInTextFile;
}
Rick Astley
  • 125
  • 1
  • 11

3 Answers3

1

This is because your code is designed to only read a single line. You need to continuously determine if readLine() produces a result and if not, discontinue reading the file.

    private String read(String file) throws IOException {
        String dataInTextFile = "";

        try (BufferedReader fileInput = new BufferedReader(new FileReader(file))) {
            String line;

            while ((line = fileInput.readLine()) != null) {
                // process line
            }
        }

        return dataInTextFile;
    }
Jason
  • 5,154
  • 2
  • 12
  • 22
1

You are only reading the first line.

    try 
    {
        dataInTextFile = fileInput.readLine(); ----> One line read.
    } 
    catch (IOException e) 
    {
        System.out.println(e);
    }

Should be -

while ((dataInTextFile = fileInput.readLine()) != null) {
System.out.println(dataInTextFile );
}
RRIL97
  • 858
  • 4
  • 9
0

Actually bufferReader.readLine() gives you one line and it moves to next line beginning cursor until the end of file(at the end of line since it can't read any more further line, it returns null).

You can read through bufferReader like this

public String readFile(String filePath) {
        StringBuilder contentString = new StringBuilder();
        try {
            BufferedReader bufferReader = new BufferedReader(new FileReader(filePath));
            String line = bufferReader.readLine();
            while(line != null){
                contentStringString.append(line);
                line = bufferReader.readLine();
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return contentString.toString();
}
mss
  • 1,423
  • 2
  • 9
  • 18