我要尝试创建目录并将数据写入该文件。我正在尝试使用 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 {
}
最佳答案
- 关闭文件
您不必关闭它,因为写入方法本身确保在写入最后一个字节后该文件将被关闭。
根据 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.
- 创建目录和写入大数据文件的正确方法。
只要您处理所有异常情况就可以了。
关于java - 如何关闭 Files.write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44983585/