Writing Output to a Text File in Java

Many times it is important to write output to a file to be saved. This is commonplace in just about every kind of Java application - from business to games. It allows the users information/status/progress to be saved or recorded for future reference. In order for this to work, the simplest solution is to create a file in the same folder as the Java program. For this example, we are going to create an output file called output.txt. There is no need to create it beforehand, as you are able to do that from within the program.
  1. import java.io.*; //necessary to use the File and FileWriter classes for creating and writing to a file
  2.  
  3. public class output
  4. {
  5.  
  6. public static void main(String[] args)
  7. {
  8.  
  9. try
  10. {
  11. File newTextFile = new File("output.txt"); //creates the file output.txt
  12.  
  13. FileWriter toFile = new FileWriter(newTextFile); //creates a FileWriter called toFile
  14.  
  15. toFile.write("Hello, world!"); //writes to the file
  16.  
  17. toFile.close();
  18.  
  19. }
  20.  
  21. catch (IOException e) //necessary exception handling. will not function without this
  22. {
  23. }
  24.  
  25. }
  26. }
As you can see, the basic output used in this example is simply "Hello, world!" This may be changed to any set of text, including numerical values. The way of storing numerical values is as follows:
  1. int n = 53;
  2. toFile.write(String.valueOf(n));
As you may have guessed, it takes the value of the integer, n, and converts it into a string. Try it yourself. Replace the text with a value that the users enter themselves. The next tutorial will be very much related to this one, so be sure to get comfortable with this the best you can! As always, leave any questions in the comments below.

Tags

Add new comment