What's the simplest way to create and write to a (text) file in Java?
Java – How to create a file and write to it
file-iojava
Related Topic
- Java – How to read / convert an InputStream into a String in Java
- Java – How to create a Java string from the contents of a file
- Java – What’s the simplest way to print a Java array
- Bash – How to tell if a regular file does not exist in Bash
- Git – How to find and restore a deleted file in a Git repository
- Java – Why is subtracting these two times (in 1927) giving a strange result
- Java – Why is processing a sorted array faster than processing an unsorted array
Best Answer
Note that each of the code samples below may throw
IOException
. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.Note that each of the code samples below will overwrite the file if it already exists
Creating a text file:
Creating a binary file:
Java 7+ users can use the
Files
class to write to files:Creating a text file:
Creating a binary file: