gpt4 book ai didi

java - 如果文件不存在,readAllLines 会返回什么?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:23:13 27 4
gpt4 key购买 nike

oracle 文档说 hereFiles.readAllLines(Path path, Charset cs)方法将文件中的行作为 List<String> 返回.
如果文件不存在会返回什么?还有哪个实现 List<String>它会回来吗?

最佳答案

这里是 Files#readAllLines(Path, Charset) 抛出的异常

它实际上使用了一个 try-with-ressources 来实例化一个 BufferedReaderpath作为参数。如果文件不存在,一个 IOException不是由它在构造函数中抛出。

Throws:

java.io.IOException if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is read

java.lang.SecurityException In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file.


ArrayList<String>用作 List<String> 的确切实现

public static List<String> readAllLines(Path path, Charset cs) throws IOException {
try (BufferedReader reader = newBufferedReader(path, cs)) {
List<String> result = new ArrayList<>(); <-------- HERE
for (;;) {
String line = reader.readLine();
if (line == null)
break;
result.add(line);
}
return result;
}
}

关于java - 如果文件不存在,readAllLines 会返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228277/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com