Reading File Using File Class in Java

There are many ways to read a text file in java. Permit'southward await at java read text file dissimilar methods one by one.

Java read text file

java read file, java read text file

At that place are many ways to read a text file in coffee. A text file is made of characters, and then we can use Reader classes. In that location are some utility classes too to read a text file in coffee.

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

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

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

We tin use Files class to read all the contents of a file into a byte array. Files course besides has a method to read all lines to a listing of string. Files class is introduced in Java 7 and it'due south good if you want to load all the file contents. You should use this method only when you are working on small files and you need all the file contents in memory.

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

Read text file in java using java.io.FileReader

You can employ FileReader to get the BufferedReader and then read files line by line. FileReader doesn't support encoding and works with the system default encoding, and so it'due south not 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); Cord line; while((line = br.readLine()) != null){     //process the line     System.out.println(line); }                      

Java read text file using java.io.BufferedReader

BufferedReader is good if you desire to read file line past line and procedure on them. It'due south good for processing the large file and it supports encoding as well.

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

                          Cord 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()) != zero){      //process the line      Organization.out.println(line); } br.shut();                      

Using scanner to read text file in java

If you want to read file line past line or based on some java regular expression, Scanner is the class to use.

Scanner breaks its input into tokens using a delimiter blueprint, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. The scanner class is not synchronized and hence not thread safe.

                          Path path = Paths.go(fileName); Scanner scanner = new Scanner(path); Organization.out.println("Read text file using Scanner"); //read line by line while(scanner.hasNextLine()){     //process each line     Cord line = scanner.nextLine();     System.out.println(line); } scanner.close();                      

Java Read File Example

Hither is the example 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 coffee.io.File; import java.io.FileInputStream; import java.io.FileReader; import coffee.io.IOException; import java.io.InputStreamReader; import coffee.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import coffee.nio.file.Path; import java.nio.file.Paths; import coffee.util.List; import java.util.Scanner;  public course JavaReadFile {      public static void main(String[] args) throws IOException {         String fileName = "/Users/pankaj/source.txt";                  //using Java 7 Files class to process pocket-size files, go consummate file data         readUsingFiles(fileName);                  //using Scanner class for large files, to read line by line         readUsingScanner(fileName);                  //read using BufferedReader, to read line by line         readUsingBufferedReader(fileName);         readUsingBufferedReaderJava7(fileName, StandardCharsets.UTF_8);         readUsingBufferedReader(fileName, StandardCharsets.UTF_8);                  //read using FileReader, no encoding support, not efficient         readUsingFileReader(fileName);     }      private static void readUsingFileReader(String fileName) throws IOException {         File file = new File(fileName);         FileReader fr = new FileReader(file);         BufferedReader br = new BufferedReader(fr);         Cord line;         System.out.println("Reading text file using FileReader");         while((line = br.readLine()) != nada){             //procedure the line             System.out.println(line);         }         br.shut();         fr.close();              }      private static void readUsingBufferedReader(Cord 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);         Cord line;         System.out.println("Read text file using InputStreamReader");         while((line = br.readLine()) != nada){             //process the line             System.out.println(line);         }         br.close();              }      individual static void readUsingBufferedReaderJava7(String fileName, Charset cs) throws IOException {         Path path = Paths.get(fileName);         BufferedReader br = Files.newBufferedReader(path, cs);         String line;         Organisation.out.println("Read text file using BufferedReader Java 7 improvement");         while((line = br.readLine()) != null){             //process the line             System.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;         System.out.println("Read text file using BufferedReader");         while((line = br.readLine()) != nada){             //procedure the line             System.out.println(line);         }         //shut resources         br.close();         fr.close();     }      individual static void readUsingScanner(String fileName) throws IOException {         Path path = Paths.become(fileName);         Scanner scanner = new Scanner(path);         Organization.out.println("Read text file using Scanner");         //read line by line         while(scanner.hasNextLine()){             //process each line             String line = scanner.nextLine();             Arrangement.out.println(line);         }         scanner.close();     }      individual static void readUsingFiles(String fileName) throws IOException {         Path path = Paths.get(fileName);         //read file to byte assortment         byte[] bytes = Files.readAllBytes(path);         System.out.println("Read text file using Files form");         //read file to String list         @SuppressWarnings("unused") 		List<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 example, if yous are just logging the file, you tin can use Files and BufferedReader. If you are looking to parse the file based on a delimiter, you lot should use Scanner grade.

Earlier I terminate this tutorial, I desire to mention near RandomAccessFile. We can apply this to read text file in java.

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

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

kimescoging.blogspot.com

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

0 Response to "Reading File Using File Class in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel