ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 35

Updated on October 16, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

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.

Source

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

Creating a new class in Java NetBeans
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 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi ChristyWrites,

      Welcome to The Java programming class. Thanks for the visit and comment.

    • ChristyWrites profile image

      Christy Birmingham 

      6 years ago from British Columbia, Canada

      Wow I wish I had time to learn all about programming! When I do, I will certainly revisit your hubs. Thanks.

    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi teaches12345,

      Thanks, always supporting and giving moral. I do appreciate the visit and comment.

    • teaches12345 profile image

      Dianna Mendez 

      6 years ago

      Keep up the exellent posting on this series!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)