簡體   English   中英

如何使用BufferedReader將txt文件中的行讀取到數組中

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

我知道如何閱讀Scanner ,但我如何使用BufferedReader 我希望能夠將行讀入數組。 我能夠將hasNext()函數與Scanner但不是BufferedReader ,這是我唯一不知道該怎么做的事情。 如何檢查何時到達文件結尾?

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++;
}

文檔指出 ,如果到達流的末尾, readLine()將返回null

通常的習慣用法是更新在while條件中保存當前行的變量,並檢查它是否不為null:

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

另外,您可能事先不知道要讀取的行數,因此我建議您使用列表而不是數組。

如果您打算閱讀所有文件的內容,則可以使用Files.readAllLines

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

readLine() 到達EOF 返回null

只是

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

當然這段代碼不是推薦的讀取文件的方法,但是如果你想要按照你想要的方式(一些預定義的大小數組,計數器等)完成它,它會顯示如何完成它。

使用readLine()try-with-resourcesVector

    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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM