Writing Output to a Text File in Java
Submitted by GeePee on Tuesday, May 12, 2015 - 23:17.
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.
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:
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.
- import java.io.*; //necessary to use the File and FileWriter classes for creating and writing to a file
- public class output
- {
- {
- try
- {
- toFile.write("Hello, world!"); //writes to the file
- toFile.close();
- }
- {
- }
- }
- }
- int n = 53;
Add new comment
- 18 views