[英]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.