How to Read an Input File in Java

Save

Computer programming languages provide tools that enable software to read and write files. This is a powerful function; it allows you to program software that can interface with files. Many programs store configuration data in files, and save their output to files. Interfacing with files is very common in software. If you want to learn file input and output, the best place to start is to learn how to read a file with a popular language such as Java.

Things You'll Need

  • Java Development Kit and Netbeans Bundle
  • Open the NetBeans software by clicking its icon. Create a new project by clicking on "File/New Project" and selecting "Java Application." A new project is created and a source code file appears in the NetBeans text editor. This file has a main function and not much else.

  • Import the Java IO library, which is used for file input and output, by adding this to the top of the source code file:

    import java.io.*;

  • Create a try/catch statement between the curly brackets of the main function. This statement will catch any error that the file input function might throw. A try/catch statement looks like this:

    try{}

    catch(Exception any){}

  • Create a data stream for reading a file. Suppose the file you want to read is called "filename.txt," and resides in the Java project folder. You would declare the data stream by writing this line in between the curly brackets of the try statement:

    DataInputStream i = new DataInputStream(new FileInputStream("filename.txt"));

  • Create an instance of BufferedReader, which will read the file using the data stream created in the previous step. Write the following below the line you wrote in the previous step:

    BufferedReader b = new BufferedReader(new InputStreamReader(i));

  • Declare a string which will hold a line of text from the file. You can do this by writing the following below the line you wrote in Step 5:

    String str;

  • Iterate through all of the lines of text in the file and print them to the console. You can accomplish this by writing a while loop like this:

    while ((str = b.readLine()) != null) { System.out.println (str); }

  • Run the program by pressing F6. The program will open up the file "filename.txt" and print its contents to the console.

Promoted By Zergnet

Comments

Resources

You May Also Like

Related Searches

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!