Reading and writing data completely using java nio

We have seen that we can create path instances and then we can create FileWriter and FileReader instances using nio with something like below

  Path instance - Path locPath = FileSystems.getDefault().getPath("locations.txt");

Creating BufferedWriter objects using path instances

try(BufferedWriter locFile = Files.newBufferedWriter(locPath);

and BufferedReader as below

 Path dirPath = FileSystems.getDefault().getPath("directions.txt");
 try(BufferedReader dirFile = Files.newBufferedReader(dirPath)){

Lets create a channel to read and write from a file

   FileInputStream file = new FileInputStream("data.txt");
   FileChannel channel = file.getChannel();

Above we have created an instance of FileInputStream and then using file.getChannel method to create an instance of channel

So instead of creating a channel lets read and write data to file using write and readAllLines methids

Each write is an individual operation so it will open file write data close file and then repeat the same procedure again.

So to avoid opening any closing files we should write data in chunks using String builder class and since data is only written in bytes so we better convert String to bytes before writing. Here we are writing "Line 5 to a new line and need to convert it to bytes and providecharset type

The last parameter StandardOpenOption is imp. Using APPEND we are telling it to append at the end of existing file.

//StandardOpenOption.TRUNCATE_EXISTING - deletes the content of current file and writes again

//StandardOpenOption.CREATE -created a new file.

Path dataPath = FileSystems.getDefault().getPath("data.txt");
    Files.write(dataPath,"\nLine 5".getBytes("UTF-8"), StandardOpenOption.APPEND);

To read lines we can create a list of lines and then read all lines and put them in the list and then we can print each line using a for loop

 List<String> lines = Files.readAllLines(dataPath);
        for(String line:lines){
            System.out.println(line);
        }
    }
    catch (IOException e){
        e.printStackTrace();
    }
}