Javascript required
Skip to content Skip to sidebar Skip to footer

How to Read From a Text File in Java

There are many means to read a text file in java. Allow'due south look at java read text file different methods ane past i.

Java read text file

java read file, java read text file

At that place are many means to read a text file in java. A text file is made of characters, and so nosotros tin can utilise Reader classes. There are some utility classes besides to read a text file in java.

  1. Java read text file using Files form
  2. Read text file in coffee using FileReader
  3. Java read text file using BufferedReader
  4. Using Scanner class to read text file in java

Now let's await at examples showing how to read a text file in coffee using these classes.

Java read text file using java.nio.file.Files

Nosotros tin can use Files class to read all the contents of a file into a byte assortment. Files class as well has a method to read all lines to a listing of string. Files class is introduced in Java 7 and information technology's skilful if you want to load all the file contents. You lot should utilize this method only when yous are working on small files and yous need all the file contents in memory.

                          String fileName = "/Users/pankaj/source.txt"; Path path = Paths.get(fileName); byte[] bytes = Files.readAllBytes(path); List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);                      

Read text file in coffee using java.io.FileReader

You can use FileReader to go the BufferedReader so read files line by line. FileReader doesn't support encoding and works with the system default encoding, so it'due south non a very efficient way of reading a text file in java.

                          String fileName = "/Users/pankaj/source.txt"; File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; while((line = br.readLine()) != nix){     //process the line     System.out.println(line); }                      

Java read text file using java.io.BufferedReader

BufferedReader is adept if you desire to read file line by line and process on them. Information technology'south adept for processing the big file and information technology supports encoding also.

BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads. BufferedReader default buffer size is 8KB.

                          String fileName = "/Users/pankaj/source.txt"; File file = new File(fileName); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, cs); BufferedReader br = new BufferedReader(isr);  String line; while((line = br.readLine()) != null){      //process the line      System.out.println(line); } br.close();                      

Using scanner to read text file in coffee

If you desire to read file line by line or based on some coffee regular expression, Scanner is the form to use.

Scanner breaks its input into tokens using a delimiter pattern, which past default matches whitespace. The resulting tokens may and so be converted into values of different types using the various side by side methods. The scanner grade is non synchronized and hence not thread safe.

                          Path path = Paths.get(fileName); Scanner scanner = new Scanner(path); System.out.println("Read text file using Scanner"); //read line by line while(scanner.hasNextLine()){     //procedure each line     String line = scanner.nextLine();     Arrangement.out.println(line); } scanner.close();                      

Java Read File Example

Here is the instance class showing how to read a text file in java. The example methods are using Scanner, Files, BufferedReader with Encoding support and FileReader.

                          package com.journaldev.files;  import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import coffee.io.InputStreamReader; import coffee.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Listing; import java.util.Scanner;  public class JavaReadFile {      public static void main(String[] args) throws IOException {         Cord fileName = "/Users/pankaj/source.txt";                  //using Coffee vii Files grade to process small files, go complete file information         readUsingFiles(fileName);                  //using Scanner class for big files, to read line by line         readUsingScanner(fileName);                  //read using BufferedReader, to read line past line         readUsingBufferedReader(fileName);         readUsingBufferedReaderJava7(fileName, StandardCharsets.UTF_8);         readUsingBufferedReader(fileName, StandardCharsets.UTF_8);                  //read using FileReader, no encoding back up, not efficient         readUsingFileReader(fileName);     }      individual static void readUsingFileReader(Cord fileName) throws IOException {         File file = new File(fileName);         FileReader fr = new FileReader(file);         BufferedReader br = new BufferedReader(fr);         String line;         Organization.out.println("Reading text file using FileReader");         while((line = br.readLine()) != nil){             //process the line             Arrangement.out.println(line);         }         br.close();         fr.close();              }      private static void readUsingBufferedReader(String fileName, Charset cs) throws IOException {         File file = new File(fileName);         FileInputStream fis = new FileInputStream(file);         InputStreamReader isr = new InputStreamReader(fis, cs);         BufferedReader br = new BufferedReader(isr);         String line;         System.out.println("Read text file using InputStreamReader");         while((line = br.readLine()) != naught){             //process the line             Arrangement.out.println(line);         }         br.close();              }      private static void readUsingBufferedReaderJava7(String fileName, Charset cs) throws IOException {         Path path = Paths.go(fileName);         BufferedReader br = Files.newBufferedReader(path, cs);         String line;         Arrangement.out.println("Read text file using BufferedReader Java seven improvement");         while((line = br.readLine()) != null){             //process the line             Arrangement.out.println(line);         }         br.close();     }      private static void readUsingBufferedReader(String fileName) throws IOException {         File file = new File(fileName);         FileReader fr = new FileReader(file);         BufferedReader br = new BufferedReader(fr);         String line;         Organisation.out.println("Read text file using BufferedReader");         while((line = br.readLine()) != null){             //process the line             System.out.println(line);         }         //close resource         br.shut();         fr.close();     }      private static void readUsingScanner(String fileName) throws IOException {         Path path = Paths.get(fileName);         Scanner scanner = new Scanner(path);         Organisation.out.println("Read text file using Scanner");         //read line by line         while(scanner.hasNextLine()){             //process each line             Cord line = scanner.nextLine();             Arrangement.out.println(line);         }         scanner.close();     }      private static void readUsingFiles(String fileName) throws IOException {         Path path = Paths.become(fileName);         //read file to byte array         byte[] bytes = Files.readAllBytes(path);         Organisation.out.println("Read text file using Files form");         //read file to String list         @SuppressWarnings("unused") 		Listing<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);         System.out.println(new String(bytes));     }  }                      

The choice of using a Scanner or BufferedReader or Files to read file depends on your project requirements. For instance, if you are just logging the file, you can use Files and BufferedReader. If y'all are looking to parse the file based on a delimiter, yous should use Scanner class.

Earlier I end this tutorial, I want to mention about RandomAccessFile. We can use this to read text file in java.

                          RandomAccessFile file = new RandomAccessFile("/Users/pankaj/Downloads/myfile.txt", "r"); String str;  while ((str = file.readLine()) != null) { 	System.out.println(str); } file.close();                      

That's all for coffee read text file example programs.

schlunketheyeaterve85.blogspot.com

Source: https://www.journaldev.com/867/java-read-text-file