how to open a text file in java

Java
// Java Program to illustrate reading from Text File 
// using Scanner Class 
import java.io.File; 
import java.util.Scanner; 
public class ReadFromFileUsingScanner 
{ 
  public static void main(String[] args) throws Exception 
  { 
    // pass the path to the file as a parameter 
    File file = 
      new File("C:\\Users\\pankaj\\Desktop\\test.txt"); 
    Scanner sc = new Scanner(file); 
  
    while (sc.hasNextLine()) 
      System.out.println(sc.nextLine()); 
  } 
} 
// Java Program to illustrate reading from FileReader 
// using Scanner Class reading entire File 
// without using loop 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 
  
public class ReadingEntireFileWithoutLoop 
{ 
  public static void main(String[] args) 
                        throws FileNotFoundException 
  { 
    File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt"); 
    Scanner sc = new Scanner(file); 
  
    // we just need to use \\Z as delimiter 
    sc.useDelimiter("\\Z"); 
  
    System.out.println(sc.next()); 
  } 
} 
// Java Program to illustrate reading from 
// FileReader using FileReader 
import java.io.*; 
public class ReadingFromFile 
{ 
  public static void main(String[] args) throws Exception 
  { 
    // pass the path to the file as a parameter 
    FileReader fr = 
      new FileReader("C:\\Users\\pankaj\\Desktop\\test.txt"); 
  
    int i; 
    while ((i=fr.read()) != -1) 
      System.out.print((char) i); 
  } 
} 
// Java program to illustrate reading data from file 
// using nio.File 
import java.util.*; 
import java.nio.charset.StandardCharsets; 
import java.nio.file.*; 
import java.io.*; 
public class ReadFileIntoList 
{ 
  public static List<String> readFileInList(String fileName) 
  { 
  
    List<String> lines = Collections.emptyList(); 
    try
    { 
      lines = 
       Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); 
    } 
  
    catch (IOException e) 
    { 
  
      // do something 
      e.printStackTrace(); 
    } 
    return lines; 
  } 
  public static void main(String[] args) 
  { 
    List l = readFileInList("C:\\Users\\pankaj\\Desktop\\test.java"); 
  
    Iterator<String> itr = l.iterator(); 
    while (itr.hasNext()) 
      System.out.println(itr.next()); 
  } 
} 
// Java Program to illustrate reading from FileReader 
// using BufferedReader 
import java.io.*; 
public class ReadFromFile2 
{ 
  public static void main(String[] args)throws Exception 
  { 
  // We need to provide file path as the parameter: 
  // double backquote is to avoid compiler interpret words 
  // like \test as \t (ie. as a escape sequence) 
  File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt"); 
  
  BufferedReader br = new BufferedReader(new FileReader(file)); 
  
  String st; 
  while ((st = br.readLine()) != null) 
    System.out.println(st); 
  } 
} 

Source

Also in Java: