- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 35
Lesson 35: How to write into text files in Java
In the previous lesson we learnt how we can manipulate text files by reading the content of a text file and displaying it on the console. That is just one way of text files manipulation, another way is to write into text files using Java code. As a programmer, you may need to store some variables or program passwords into a text file.
Another common way of using text files in programming is when you need to store SQL (Structured Query Language) statements as text strings. You can manipulate these SQL statements such as SQL SELECT statements or host statements when accessing a database. We’ll learn about Java and Databases in later lessons. In this lesson, we shall learn how we can use Java programming codes to write into text files.
Writing into text files in Java is a little bit easier than reading from text files as we did in Lesson 34. We’ll need to use Java inbuilt classes that write into files i.e. FileWriter and PrintWriter classes.
Open the Java NetBeans code window and create a new class in the package where we had the class for reading a text file i.e. the Textfiles package. If you did name this packages with your own preferred name then select the package.
Right click on the package, select New >> Java class. You can name the class with a name of your choice but here we’ll call it WriteTextFile.
Creating a new class in Java NetBeans
Once you have created the class, import the following Java classes into the new class as shown in the image below:
When writing into text files we can choose between two ways of writing into the file; we can either overwrite the content of the text file or append into the text file. So you can either choose between appending the file or not. The class FileWriter that we added in the program will help us to do that.
What we need to do is to add a Boolean variable in the program that specifies the mode of writing into the text file. We’ll set the value of the Boolean variable to false which is the default value for the FileWriter class. The Boolean values of false means “Don’t append the file, overwrite everything.” We’ll also need another variable to hold the file path.
Because we’ll create a new object from WriteTextFile class, we need to create a constructor to initialize the file path variable. In fact we can set up two constructors; one to initialize the file path and another to initialize the Boolean variable in case we want to append the text file. Modify the program so that it has the two variables and the two constructors as shown below:
In the above image, we have declared a string variable called mypath to hold the file path and another Boolean variable called append which is set to false. There are also two constructors as discussed earlier.
The first constructor with one variable only, file_path, can be used when we want to overwrite the text file while the other constructor with two variables, file_path and append_value, can be used when appending a text file.
Now we need to create a new method to write into the text file. We’ll call this method WriteToFile and then we’ll create an object of the FileWriter class inside this new method and pass the variables containing file path and append mode. In this case, we’ll use the second constructor. Modify the program so as to look like shown below:
In the above image, we have created the method WriteToFile and passed a string variable textline that will contain the text to write into a text file. We have also included the "throws IOException" keyword like we did earlier to trap the probable file errors. Inside the method, we have created an object of the FileWriter class with the file path variable, mypath, and the append variable for appending mode.
Since the FileWriter class writes text as bytes, we’ll need a method in the PrintWriter class to write the text. We have created an object of the PrintWriter class and inside we have passed the name of the FileWriter class.
Now, the method we shall use from the PrintWriter class is the printf method. This is because we need to take care of cross platforms when writing text files. This method will enable us to write text files on both Windows and Unix platforms even if the new line character is different.
With the printf method, we need to format the text to be written such that we can write line by line and at the end of the line we put a new line. After writing the text, we need to close the printf method. The lines of statement to do so are shown below, add them in the program.
myline.printf( "%s" + "%n" , textLine);
myline.close();
The %s tells Java that we need to read a text of any length line by line and the %n tells Java to put a new line after every line of text. The text that we want to write is passed in the variable textline. The program now should look like shown below, you can copy and paste the code:
Java program to write into text files
package textfiles; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; public class WriteTextFile{ private String mypath; private boolean append = false; public WriteTextFile(String file_path){ mypath = file_path; } public WriteTextFile(String file_path , boolean append_value){ mypath = file_path; append = append_value; } public void WriteToFile( String textLine ) throws IOException{ FileWriter write = new FileWriter(mypath, append); PrintWriter myline = new PrintWriter(write); myline.printf( "%s" + "%n" , textLine); myline.close(); } }
Now, our program is ready, all we need to do is go back to the main class i.e. the TextFile class we had in the previous lesson and do some modifications. We’ll use the "C:/Myfile/testfile.txt" text file we had created earlier to append an extra text. We’ll ask the user to enter the text to be appended in dialog box so insert the following statement at the top of the main class just after the package name:
import javax.swing.JOptionPane;
Then, inside the main class just after the try…catch block add another try…catch block. Because we are not deleting the previous code, we’ll need a line to separate the first output and the new output. After that, create an object of the WriteTextFile class and pass the text to be written in a dialog box. What follows after is an array and a FOR loop to go through the array of text and output the new appended text. Here is the complete code of the main class:
Writing into text file: Java main class
package textfiles; import java.io.IOException; import javax.swing.JOptionPane; public class TextFiles { public static void main(String[] args)throws IOException{ String file_name = "C:/Myfile/testfile.txt"; //Reading a text file try{ ReadFile file = new ReadFile(file_name); String[ ]aryLines = file.OpenFile(); int i; for ( i=0; i < aryLines.length; i++ ) { System.out.println(aryLines[i]) ; } }catch ( IOException e ) { System.out.println( e.getMessage() ); } //Writing into a text file try{ System.out.println("---------------------------------------------"); WriteTextFile Newdata = new WriteTextFile(file_name , true); Newdata.WriteToFile(JOptionPane.showInputDialog("Enter text to append")); ReadFile file = new ReadFile(file_name); String[ ]aryLines = file.OpenFile(); int i; for ( i=0; i < aryLines.length; i++ ) { System.out.println(aryLines[i]) ; } }catch ( IOException e ) { System.out.println( e.getMessage() ); } } }
Run the main class and what you should get is the first output followed by the dialog box to enter the text to append. Enter some text and click “Ok.”
And here is the final output, both on the console and in the Notepad text file:
Java console output
Text file in Notepad
Congratulation! You have completed another milestone in Java programming. Now you are able to manipulate text files by reading data from text files and writing data into text files. Go ahead and do some practice as the concept of working with text files is very useful in any programming language.
In the coming lessons, we shall spend a lengthy time working with Java forms. We’ll learn how to work with Graphical User Interfaces (GUI) in Java NetBeans and how to manipulate various GUI controls in Java. See you then.
<< Lesson 34 | Lesson 36 >>
Other related hubs...
- Programming In Java - A Step By Step Tutorial For Beginners: Lesson 23
Java programming language has many inbuilt methods that can be used to enhance the functionality of a program. In this article, i will discuss the use of Java equals() and charAt() methods and how to use these methods in Java including sample ... - Programming In Java - A Step By Step Tutorial For Beginners: Lesson 2
In this lesson you will learn how to create your first Java project and how to interpret the NetBeans code editor window. - Programming In Java - A Step By Step Tutorial For Beginners: Lesson 10
The FOR loop is one of the most common looping controls used in Java. The FOR loop forces the program to repeat a statement or a group of statements a specified number of times. It has three parts; the initial value part, condition part, and ... - Programming In Java - A Step By Step Tutorial For Beginners: Lesson 5
One of the useful classes that handle inputs from a user in Java is the Scanner class. The Scanner class is located in the util (utility) package of the Java library.
4