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.
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.
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();
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)
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();
}
}
}
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.
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.