import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter(“out.txt”);
BufferedWriter out = new BufferedWriter(fstream);
out.write(“Hello Java”);
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println(“Error: ” + e.getMessage());
}
}
}
The above is a simple way of creating a file, writing into it and then closing it. There is one other way, which is nicer, as follow:
fileStream = new PrintStream(new FileOutputStream(“out.txt”,true));
// Redirecting console output to file
System.setOut(fileStream);
// Redirecting runtime exceptions to file
This way, you are setting the system.out to a file. After that, anything you put on the output buffer instead of printing it out on the console, it will be printed in a file system.