[英]Write from file to ArrayList
程序要运行,需要从文件中向arraylist写入数据,但是循环中如何让写入的元素不等于null呢? 也就是说,一旦从文件中读取所有行,循环就会停止执行
public static void readFromFile(String path, String filename) throws IOException {
ArrayList<String> ip = new ArrayList<>();
try {
File file = new File(path + "\\" + filename);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
ip.add(br.readLine());
while ((ip.add(br.readLine()) != null)) {
//writing to a variable
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
ip.add(...)
返回一个boolean
。 这段代码无法编译,因为boolean
是一个原语,因此永远不可能是 null。
将add
移动到循环内:
String line;
while ((line = br.readLine()) != null) {
ip.add(line);
}
这是阅读所有行的更好方法:
Files.readAllLines(Paths.get("path_to_file"), StandardCharsets.UTF_8)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.