tags:

views:

93

answers:

5

What's the simplest way to create and write to a file in Java?

I know this is a very basic question, but the web is full of different answers for different versions of Java and it would be nice to have an answer here on StackOverflow.

+8  A: 

Creating a text file (note that this will overwrite the file if it already exists):

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creating a binary file (will also overwrite the file):

byte dataToWrite[] = //...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(dataToWrite);
out.close();
Michael Angstadt
The PrintWriter should specify an encoding, though.
Michael Borgwardt
@Michael: Like that? (see edit)
Michael Angstadt
Worth noting PrintWriter will truncate the filesize to zero if the file already exists
Covar
@Covar True, thanks
Michael Angstadt
PrintWriter can be (and often is) used, but is not (conceptually) the right class for the job. From the docs: `"PrintWriter prints formatted representations of objects to a text-output stream. "`Bozho's answer is more correct, though it looks cumbersome (you can always wrap it in some utility method).
leonbloy
@mangest, yes better now ;)
Michael Borgwardt
+6  A: 
Writer writer = null;

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

See also here (includes NIO2)

Bozho
This is the correct way to right to a text file, though the BufferedWriter filter is not always beneficial, and the encoding should be passed as argument. +1 for specifyng the encoding, though.
leonbloy
+3  A: 
public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        try {
          File file = new File("example.txt");
          BufferedWriter output = new BufferedWriter(new FileWriter(file));
          output.write(text);
          output.close();
        } catch ( IOException e ) {
           e.printStackTrace();
        }
    }
}
Eric Petroelje
+6  A: 

If you wish to have a relatively pain-free experience you can also have a look at the apache commons IO package, more specifically the FileUtils class.

Never forget to check third-party libraries. Yoda time for date manipulation, StringUtils for common string operations and such can make your code more readable.

Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.

extraneon
+3  A: 

If you for some reason want to separate the act of creating and writing, the Java equivalent of touch is

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile() does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.

Mark Peters