java - 如何关闭 Files.write

标签 java io nio

我要尝试创建目录并将数据写入该文件。我正在尝试使用 java nio 来更有效地编写文件。我的疑问是在下面写完之后如何关闭它是我的代码。请给我建议。

这是创建目录和写入大型数据文件 [200 kb] 的正确方法吗。

    java.nio.file.Path path = java.nio.file.Paths.get(filePath);

    try {
        if (!java.nio.file.Files.exists(path)) {
            java.nio.file.Files.createDirectories(path.getParent());
            path = java.nio.file.Files.createFile(path);
            path = java.nio.file.Files.write(path, data.getBytes());
        } else {
            java.nio.file.Files.write(path, data.getBytes("utf-8"), 
                    java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }

最佳答案

  1. 关闭文件

您不必关闭它,因为写入方法本身确保在写入最后一个字节后该文件将被关闭。

根据 Files.write() 的描述方法。

Writes bytes to a file. The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. All bytes in the byte array are written to the file. The method ensures that the file is closed when all bytes have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.

  1. 创建目录和写入大数据文件的正确方法。

只要您处理所有异常情况就可以了。

关于java - 如何关闭 Files.write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44983585/

相关文章:

go - 如何在stdout/stderr中显示命令输出,同时还将输出保存到Go中的变量中?

java - Nio Selector.select IO 准备情况

perl - perl read() 函数和不是 ref 的缓冲区背后的魔法是什么?

java - 目标目录中没有 Application.class。在注册表中找不到应用程序

java - 如何以编程方式配置 Jetty 以执行 JSP 页面?

java - 如何在 AIX 中运行 jar 文件?

c++ - fstream::read 的结果不一致

Java:文件重命名检测

java - HTTP 的 SSL 重新协商工作流程

java - 使用random时如何让每个ImageView显示不同的图片?安卓工作室