Java – How to create and write to a file

In Java, we can use Files.write (Since JDK 7) to create and write to a file, one line, simple and nice. See the following examples :


	Charset utf8 = StandardCharsets.UTF_8;
	List<String> list = Arrays.asList("Line 1", "Line 2");
	
	// If the file doesn't exists, create and write to it
	// If the file exists, truncate (remove all content) and write to it
	Files.write(Paths.get("app.log"), list, utf8);

	// If the file doesn't exists, create and write to it
	// If the file exists, append to it
	Files.write(Paths.get("app.log"), list, utf8, 
		StandardOpenOption.CREATE, StandardOpenOption.APPEND);

	// For a single line String
	Files.write(Paths.get("app.log"), "Hello World".getBytes());

	// Create and write to a file in binary format
	byte[] bytes = {1, 2, 3, 4, 5};
	Files.write(Paths.get("app.bin"), bytes);

1. Files.write

A complete Java NIO Files.write example.

FileExample.java

package com.mkyong;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class FileExample {

    public static void main(String[] args) {

        Charset utf8 = StandardCharsets.UTF_8;
        List<String> list = Arrays.asList("Line 1", "Line 2");
       
        try {
			// If the file doesn't exists, create and write to it
			// If the file exists, truncate (remove all content) and write to it
            Files.write(Paths.get("app.log"), list, utf8);
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }

        // Read
        try {
            byte[] content = Files.readAllBytes(Paths.get("app.log"));
            System.out.println(new String(content));
			
			// for binary
            //System.out.println(Arrays.toString(content));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}

Output

app.log

Line 1
Line 2

2. BufferedWriter

A complete BufferedWriter example.

BufferedWriterExample.java

package com.mkyong.calculator;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

public class BufferedWriterExample {

    public static void main(String[] args) {

        Charset utf8 = StandardCharsets.UTF_8;

        List<String> list = Arrays.asList("Line 1", "Line 2");
        String content = "Hello World";

        try (Writer writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream("app.log"), utf8)
        )) {

            writer.write(content + "\n");

            for (String s : list) {
                writer.write(s + "\n");
            }

        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        }

    }
}

Output

app.log

Hello World
Line 1
Line 2

For append, pass a true as second argument for FileOutputStream.


	try (Writer writer = new BufferedWriter(
			new OutputStreamWriter(new FileOutputStream("app.log", true), utf8)
	))

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
San Recent comment authors
newest oldest most voted
San
Guest
San

Note:It affect only kind of Microsoft proprietary document format (like Docx,doc, XLSX and XLS) Recently we migrated to new linux machine . We have a java process runs in new linux mahcine where we are able to generate the docx,xls,doc, html etc… uisng java code and place the file in the linux machine I have downloaded the file in windows and try to open it’s getting exception stating File is Corrupt and Cannot be opened. Where as i am able to open .html files successfully. Is there any softwares i need to install in new linux machine (Since it’s working… Read more »