This tutorial will teach you about Reading Text File Using Java. Text is a type of file contains a .txt extension.
This tutorial uses BufferedWriter, FileNotFoundException, IOException, FileReader, and Scanner Libraries. When the program performs reading, the program read the file from your Netbeans project. Netbeans project usually located in Documents. Please follow all the steps to complete this tutorial.
Reading a Text file in java Steps
- Create a new Java Class and name it what you want.
2. Insert the following import above your Class.
[java]import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;[/java]
3. Inside your main method, declare the following variables. Declare a scanner, string, and Buffer Reader variables.
[java]Scanner input = new Scanner(System.in);
String fileName;
String line = null;
BufferedReader bufferedReader = null;[/java]
4. Insert the following statement for user input
[java]System.out.print(“Enter file name to read: “);
fileName = input.nextLine();[/java]
5. After step 4, insert the following codes below for reading the file.
[java]try{
FileReader fileReader = new FileReader(fileName + “.txt”);
bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
}catch(FileNotFoundException ex){
System.out.println(“Unable to open the file!”);
}catch(IOException ex){
System.out.println(“Error reading file!”);
}finally{
try{
if (bufferedReader != null){
bufferedReader.close();
}
}catch(IOException e){
}
}[/java]
6. The output should look like the image below.
7. Complete Source Code
[java]import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class FileReading {
public static void main(String args[]) throws IOException{
Scanner input = new Scanner(System.in);
String fileName;
String line = null;
BufferedReader bufferedReader = null;
System.out.print(“Enter file name to read: “);
fileName = input.nextLine();
try{
FileReader fileReader = new FileReader(fileName + “.txt”);
bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
}catch(FileNotFoundException ex){
System.out.println(“Unable to open the file!”);
}catch(IOException ex){
System.out.println(“Error reading file!”);
}finally{
try{
if (bufferedReader != null){
bufferedReader.close();
}
}catch(IOException e){
}
}
}
}[/java]
About The Reading Text File In Java
Project Name: | Reading Text File |
Language/s Used: | JAVA |
Database: | None |
Type: | Desktop Application |
Developer: | IT SOURCECODE |
Updates: | 0 |
If you have question or suggestion about Reading Text File Using Java progam, please feel free to contaact us at our Contact Page.