How to open and read text file in java

In this post we are going to learn how to open and read text file in java.

how to open and read text file in java

In java open and read file there are many ways. First let’s see open and read file example java program.

Also read – java if else

How to open and read text file in java

import java.io.*;

public class OpenReadFile
{
   public static void main(String[] args) throws IOException 
   { 
      File fl = new File("D:\\JavaProject\\sachin\\demo.txt"); 
      BufferedReader read = new BufferedReader(new FileReader(fl));
      String str;
      while((str = read.readLine()) != null)
      {
         System.out.println(str);
      }
      read.close();
   }
}

In the above java program we have used FileReader and BufferedReader class. BufferedReader class has method readLine() which reads a String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.

Then each line is read using readLine() method and assigned to String variable “str”. Lastly IOException is used to handle specific exceptions.


Java FileReader class

import java.io.FileReader;

public class OpenReadDemo 
{
   public static void main(String[] args) throws Exception 
   {
      FileReader file = new FileReader("D:\\JavaProject\\sachin\\demo.txt");
      int a; 
      while((a = file.read()) != -1)
      {
         System.out.print((char) a);
      }
      file.close();
   }
}

In the above java program we have used FileReader class for reading character files. It’s also called as convenience class.

FileReader class constructors accept default character encoding and the default byte-buffersize are appropriate.


Java scanner class

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFromScanner
{
public static void main(String[] args) throws FileNotFoundException
{
// passing path to file as parameter
File fl = new File("D:\\JavaProject\\sachin\\demo.txt");
Scanner sc = new Scanner(fl);
while(sc.hasNextLine())
{
System.out.println(sc.nextLine());
}
sc.close();
}
}

Scanner class parses primitive data types using regular expressions. Input is broken using delimiter pattern.


Without using loops

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadWithoutLoop
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("D:\\JavaProject\\sachin\\demo.txt");
Scanner sc = new Scanner(file);
// use \\Z as delimiter
sc.useDelimiter("\\Z");
System.out.println(sc.next());
sc.close();
}
}


Read file from list

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class ReadFileFromList
{
public static List<String> readList(String name)
{
List<String> li = Collections.emptyList();
try
{
li = Files.readAllLines(Paths.get(name), StandardCharsets.UTF_8);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
return li;
}

public static void main(String[] args)
{
List list = readList("D:\\JavaProject\\sachin\\demo.txt");
Iterator<String> itr = list.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

readAllLines() method reads all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtimeexception, is thrown.

public static List<String> readAllLines(Path path, Charset cs) throws IOException

Bytes from the file are decoded into characters using the specified charset.


Read file as string

import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadFileAsString
{
public static String readString(String name)throws Exception
{
String str = "";
str = new String(Files.readAllBytes(Paths.get(name)));
return str;
}

public static void main(String[] args) throws Exception
{
String strInput = readString("D:\\JavaProject\\sachin\\demo.txt");
System.out.println(strInput);
}
}

Related Posts