簡體   English   中英

如何讀取文件,每一行都是Java中ArrayList中的元素?

[英]How do I read in a file, each line being an element in an ArrayList in Java?

我想獲取一個txt文件,並使該文件的每一行依次成為ArrayList中的一個元素。 我也不希望每行末尾有“ \\ n”。 我將如何處理?

我找到了,可以用JDK7制成:

List<String> readSmallTextFile(String aFileName) throws IOException {
    Path path = Paths.get(aFileName);
    return Files.readAllLines(path, ENCODING);
}

並用

ArrayList<String> foo = (ArrayList<String>)readSmallTextFile("bar.txt");

之后,您可以過濾列表“ foo”中每一行中的所有不需要的字符。

這需要三個簡單的步驟:-

  • 讀取文件中的每一行
  • 從末尾刪除換行符
  • 將行添加到ArrayList<String>

你看,我沒有回答你的問題。 我只是重新構圖,看起來像一個答案。

這就是while循環條件的樣子:-

Scanner scanner = new Scanner(yourFileObj);
while (scanner.hasNextLine()) {

    // nextLine automatically strips `newline` from the end
    String line = scanner.nextLine();  

    // Add your line to your list.
}

更新 :-

由於您逐行讀取file ,因此最好使用BufferedReader 如果您想解析 each令牌並對它們做一些特殊的事情, 掃描儀會更好。

BufferedReader br = new BufferedReader(new FileReader("fileName"));

String line = null;

// readLine also doesn't include the newline in the line read
while ((line = br.readLine()) != null) {  
    //add your line to the list
}

我更喜歡BufferedReader,它比Scanner更快

BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );

讀取直到文件結尾為

String line = br.readLine(); // read firt line
while ( line != null ) { // read until end of file (EOF)
    // process line
    line = br.readLine(); // read next line
}

暫無
暫無

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

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