How to Input Java Files
The Java programming language has the ability to read files as input. This is useful for many programs that rely on large amounts of data. If the user had to input data manually every time a program was run, it would quickly become tedious. Instead, by entering data once into a file, that file can be used repeatedly as input in a Java program. Accepting input from files is an important feature of a programming language. If you want to expand your Java programming ability, you should learn how to use files as input.
Things You'll Need
- Java Software Development Kit with NetBeans Integrated Development Environment (IDE) Bundle (see Resource for link)
Instructions
-
-
1
Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Application" from the list on the right-hand side of the screen. A new source code file appears in the NetBeans text editor. The source code file contains an empty main function.
-
2
Import the Java IO package by writing the following statement at the top of the source code file:
import java.io.*;
-
-
3
Create a try/catch block. You will use the Java BufferedReader class for file input, and this class throws exceptions. Exceptions are errors that occur when something unexpected happens, like when you try to open a file that doesn't exist. To create a try/catch block, write the following within the curly brackets of the main function:
try {}
catch(Exception e)
-
4
Create a BufferedReader instance named 'br,' by writing the following within the curly brackets of the try block:
BufferedReader br;
-
5
Create a new BufferedReader object and assign it to 'br.' To open a file named 'input.txt,' pass a new instance of FileReader into the BufferedReader constructor like this:
br = new BufferedReader(new FileReader("input.txt"));
-
6
Create a string named 'tmp' like this:
String tmp;
-
7
Read lines from the text file using the BufferedReader method 'readLine.' This method reads entire lines every time it is called. Since the text file 'input.txt' may contain multiple lines, you must call 'readLine' multiple times. The easiest way to do this is place 'readLine' inside a while loop. When the 'readLine' method reaches the end of the file, it will return a null string. You can terminate the while loop when the readLine functions returns null, like this:
while( (tmp = br.readLine()) != null)
{
}
-
8
Print out the string 'tmp' every time the while loop iterates by placing the following statement within the curly brackets of the while loop:
System.out.println(tmp);
-
9
Close the BufferedReader by placing this statement after the closing curly bracket of the while loop:
br.close();
-
10
Execute the program by pressing "F6." The program reads the file 'filename.txt' and prints out the text it contains. If the program can't find the file, it throws an exception and quits.
-
1