Java Program To Read Data From The Text File
=============================================================
How To Read Data From The Text File:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadDataFromTextFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("C:\\Users\\lenovo\\Desktop\\test.txt");
// Read the File From the Location Present inside the PC / Disc.
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
}
}
Note: In this Program, the test.txt file is stored in the Computer / Laptop on Disk.
output:
===========
Welcome To Java Programming!
Approach -2
==============
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadDataFromTextFile2 {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:\\Users\\lenovo\\Desktop\\test.txt");
Scanner sc = new Scanner(file);
// To Read Content From the File We need Loop Statement
while (sc.hasNextLine()) // To check there are more lines or not
{
System.out.println(sc.nextLine()); // Actually used to read the lines
}
sc.close();
}
}
output:
=========
Welcome To Java Programming!
Approach -3:
===============
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadDataFromTextFile3 {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:\\Users\\lenovo\\Desktop\\test.txt");
Scanner sc = new Scanner(file);
sc.useDelimiter("\\z");
System.out.println(sc.next());
sc.close();
}
}
output:
============
Welcome To Java Programming!
Comments
Post a Comment