In Java, there are many of ways to writing text to file. The following is one of the simplest ways to create a file and write text to it.
The following uses a 'try with resources' block to handle creating our 'output.txt' file. This try block also takes care of closing our file and catching any exceptions that could occur. In this instance, an exceptional event could include not having permission to create the file. We write a single line of text to our file and that is all!
try(var fw = new FileWriter("output.txt")){
fw.write("Hello World!\n");
}catch(IOException e){
// Problem writing file...
}
The 'write' function does not put a new line character at the end so we use '\n'. Although this is fine, we can use the better 'System.lineSeparator()' which adds the correct end of line terminator for the system the program is being run on as shown below.
This is exactly the same method as above. To demonstrate, the fragment below uses an enhanced for loop to get text from a String array and write it to the file.
String mytext[]={"Hello","World","from","Java!"};
for(var line:mytext){
fw.write(line+System.lineSeparator());
}
With the Java JDK installed, from a command line:
If you do not have Java JDK installed, click the following link to find out how to install Java on your computer!
import java.io.*;
class Writetext{
public static void main(){
final String myfile="output.txt";
String mytext[]={"Hello","World","from","Java!"};
try(var fw = new FileWriter(myfile)){
for(var line:mytext){
fw.write(line+System.lineSeparator());
}
System.out.println("File "+myfile+" saved!");
}catch(IOException e){
// Problem writing file...
System.out.println("There was a problem writing to "+myfile);
System.out.println(e);
}
}
}
Updated (30/10/2026)
Java File Handling:
Read Text |
Write Text |
Read Binary |
Write Binary