Georgi Koemdzhiev Georgi Koemdzhiev - 4 months ago 22
Java Question

What is the simplest way to write a text file in java

Hello, 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 :D
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();
}
}


}

Answer

Your code is the simplest. But, i always try to optimize the code further. Here is a sample.

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
    bw.write("Hello, This is a test message");
    bw.close();
    }catch (FileNotFoundException ex) {
    System.out.println(ex.toString());
    }
Comments