Java – Simplest Way to Write a Text File

filejavatext

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner 😀

I searched the web and found this code, but I understand 50% of it.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

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

        String content = "This is the content to write into file";

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Best Answer

With Java 7 and up, a one liner using Files:

String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
Related Question