Java IO / NIO

IO : java.io*;
stream oriented.
synchronous (blocking thread)
can’ t move forth and back in the stream

NIO : java.nio*;
buffer/block oriented.
asynchronous (non blocking thread)

Reading/writing CSV file:
String path = "C:/tmp/file.csv";

String content = new String(Files.readAllBytes(Paths.get(path)));
List<String> strings = Files.readAllLines(Paths.get(""), StandardCharsets.UTF_8);

for (String str : strings){
    str.replace(",", ";");
}

Files.write(Paths.get(path),strings,StandardCharsets.UTF_8);
Reading text file:
StringBuilder contents = new StringBuilder();
try {
   BufferedReader input = new BufferedReader(new FileReader(aFile));
   try {
      String line = null;
      while (( line = input.readLine()) != null){
         contents.append(line);
      }
   } finally {
      input.close();
   }
} catch (IOException ex){
   ex.printStackTrace();
}
System.println(contents.toString());
Writing text file:
File file = new File(path);
Writer output = new BufferedWriter(new FileWriter(file));
try {
    for (String str : strings){
        output.write(str);
    }
}
finally {
    output.close();
}

Leave a comment