![](/img/trans.png)
[英]Java: How do you read each line of a text file and setting each line as an array element?
[英]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.