简体   繁体   中英

How do I use BufferedReader to read lines from a txt file into an array

I know how to read in lines with Scanner , but how do I use a BufferedReader ? I want to be able to read lines into an array. I am able to use the hasNext() function with a Scanner but not a BufferedReader , that is the only thing I don't know how to do. How do I check when the end of the file text has been reached?

BufferedReader reader = new BufferedReader(new FileReader("weblog.txt"));

String[] fileRead = new String[2990];
int count = 0;

while (fileRead[count] != null) {
    fileRead[count] = reader.readLine();
    count++;
}

The documentation states that readLine() returns null if the end of the stream is reached.

The usual idiom is to update the variable that holds the current line in the while condition and check if it's not null:

String currentLine;
while((currentLine = reader.readLine()) != null) {
   //do something with line
}

As an aside, you might not know in advance the number of lines you will read, so I suggest you use a list instead of an array.

If you plan to read all the file's content, you can use Files.readAllLines instead:

//or whatever the file is encoded with
List<String> list = Files.readAllLines(Paths.get("weblog.txt"), StandardCharsets.UTF_8);

readLine() returns null after reaching EOF .

Just

do {
  fileRead[count] = reader.readLine();
  count++;
} while (fileRead[count-1]) != null);

Of course this piece of code is not the recommended way of reading the file, but shows how it might be done if you want to do it exactly the way you attempted to ( some predefined size array, counter etc. )

using readLine() , try-with-resources and Vector

    try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\weblog.txt")))
    {
        String line;
        Vector<String> fileRead = new Vector<String>();

        while ((line = bufferedReader.readLine()) != null) {
            fileRead.add(line);
        }

    } catch (IOException exception) {
        exception.printStackTrace();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM