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();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s