Write to file

Setup

private static final String FILE_PATH = "com/levelup/java/io/write-to-file.txt";
private URI fileLocation;

@Before
public void setUp() throws URISyntaxException {
    fileLocation = this.getClass().getClassLoader().getResource(FILE_PATH).toURI();
}

Straight up Java

BufferedWriter

@Test
public void write_to_file_java () throws IOException {

    File file = new File(fileLocation);

    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    out.write("writing to a file");
    out.close();
}

Java 7 File I/O

@Test
public void write_to_file_nio () throws IOException {
    
    Path path = Paths.get(fileLocation);
    
    java.nio.file.Files.write(path, "writing to a file".getBytes(), StandardOpenOption.WRITE);
}

Google Guava

@Test
public void write_to_file_guava () throws IOException {
    
    File file = new File(fileLocation);

    Files.write("writing to a file", file, Charsets.UTF_8);

}

Apache Commons

@Test
public void write_to_file_apache () throws IOException {

    File file = new File(fileLocation);

    FileUtils.write(file, "writing to file");

}