Close

Different ways to write files in Java

If you ever wanted to write a file using Java, you can find different ways to do it. Some of them are as follow:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *