Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close Files.write

Tags:

java

io

nio

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 {
    }
like image 794
deadend Avatar asked Dec 24 '22 16:12

deadend


1 Answers

  1. Closing file

You do not have to close it as the write method itself ensurer's that file will be closed once last byte is written.

As per description of Files.write() method.

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. Correct way to create directory and write large data files.

It's fine as long as you handle all exception conditions.

like image 177
Umesh Aawte Avatar answered Dec 31 '22 14:12

Umesh Aawte