25 April 2014

Java7 nio2

The Java7 introduces very handy package to operate with Files. the package is java.nio.file.

You can see Java tutorial to know about it.

Follow is an example on how writing files become easy!


package nestedclasses;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Example {
    public static void main(String[] args) {

        Path tmpPath = Paths.get("/tmp/tmp.txt");

        byte[] bytes = "Hello World\nIn Java7\n"
                .getBytes(StandardCharsets.UTF_8);

        try {
            Files.write(tmpPath, bytes, StandardOpenOption.TRUNCATE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Good luck!

No comments: