I am to attempting to create directory and write data into that file. I am trying to use java nio to write file for more efficiently. My doubt is how to close it after write it below is my code. Please advice me.
And is this correct way to create directory and write large data files [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
, with Java 11 you can just do it using Files.writeString which saves you having to callgetBytes
.