Home > DeveloperSection > Forums > How to create a file and write to a file in Java?
Derek Honeybun
Derek Honeybun

Total Post:17

Points:119
Posted on    July-16-2015 10:15 PM

 Java Java 
Ratings:


 1 Reply(s)
 459  View(s)
Rate this:
What's the simplest way to create and write to a (text) file in Java?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    July-17-2015 8:27 AM

Writer writer = null;
try {
    writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream("filename.txt"), "utf-8"));
    writer.write("Something");
} catch (IOException ex) {
  // report
} finally {
   try {writer.close();} catch (Exception ex) {/*ignore*/}
}

AND :
public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
            if ( output != null ) output.close();
        }
    }
}

Don't want to miss updates? Please click the below button!

Follow MindStick