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

标签 java file

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/

相关文章:

java - 检查最终实例变量是否已初始化

java - 使用 OpenEJB 控制无状态 session Bean 的名称

java - 试图让 Android 设备进入休眠状态,但 PowerManager 不包含“goToSleep(long) 方法

java - 多线程与类

c++ - Linux 和 Windows c++ 上的低级文件操作处理

file - Powershell-列出子目录并为每个子目录计数文件

android - 输入类型 ="file"接受 ="image/*"在电话间隙中不起作用?

c++ - 使用 mmap 逐行读取文件

Java Web 应用程序部署 Heroku

python - 如何读取和写入单个目录中的多个文件? Python