How to Read Text Files From a Folder in Java

There are many ways to read a text file in java. Let's look at coffee read text file different methods i by ane.

Coffee read text file

java read file, java read text file

There are many ways to read a text file in coffee. A text file is fabricated of characters, so we can apply Reader classes. There 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 java using FileReader
  3. Java read text file using BufferedReader
  4. Using Scanner class to read text file in coffee

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

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

We can use Files class to read all the contents of a file into a byte array. Files class also has a method to read all lines to a listing of string. Files class is introduced in Java 7 and it's good if you want to load all the file contents. You should use this method only when you are working on pocket-sized files and you lot demand 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 get the BufferedReader and then read files line by line. FileReader doesn't back up encoding and works with the system default encoding, so it's not a very efficient fashion of reading a text file in coffee.

                          Cord 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()) != null){     //process the line     System.out.println(line); }                      

Java read text file using java.io.BufferedReader

BufferedReader is good if y'all want to read file line by line and process on them. It'due south practiced for processing the large file and it supports encoding likewise.

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

Using scanner to read text file in java

If y'all want to read file line by line or based on some java regular expression, Scanner is the class to utilise.

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

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

Coffee Read File Example

Here is the instance course 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 coffee.io.FileReader; import coffee.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.List; import java.util.Scanner;  public class JavaReadFile {      public static void main(Cord[] args) throws IOException {         String fileName = "/Users/pankaj/source.txt";                  //using Coffee seven Files class to procedure small files, get complete file data         readUsingFiles(fileName);                  //using Scanner class for large files, to read line past 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 back up, 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);         String line;         Organisation.out.println("Reading text file using FileReader");         while((line = br.readLine()) != null){             //process the line             System.out.println(line);         }         br.close();         fr.shut();              }      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);         String line;         System.out.println("Read text file using InputStreamReader");         while((line = br.readLine()) != null){             //process the line             System.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;         System.out.println("Read text file using BufferedReader Java vii improvement");         while((line = br.readLine()) != null){             //procedure the line             System.out.println(line);         }         br.shut();     }      private static void readUsingBufferedReader(Cord fileName) throws IOException {         File file = new File(fileName);         FileReader fr = new FileReader(file);         BufferedReader br = new BufferedReader(fr);         String line;         Organization.out.println("Read text file using BufferedReader");         while((line = br.readLine()) != null){             //procedure the line             System.out.println(line);         }         //close resource         br.close();         fr.close();     }      private static void readUsingScanner(String fileName) throws IOException {         Path path = Paths.get(fileName);         Scanner scanner = new Scanner(path);         System.out.println("Read text file using Scanner");         //read line past line         while(scanner.hasNextLine()){             //procedure each line             String line = scanner.nextLine();             System.out.println(line);         }         scanner.close();     }      private 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 class");         //read file to String list         @SuppressWarnings("unused") 		List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);         System.out.println(new String(bytes));     }  }                      

The pick of using a Scanner or BufferedReader or Files to read file depends on your project requirements. For example, if you are simply logging the file, you tin can utilize Files and BufferedReader. If yous are looking to parse the file based on a delimiter, you should use Scanner course.

Before I end this tutorial, I want to mention almost RandomAccessFile. Nosotros can use this to read text file in coffee.

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

That'due south all for java read text file instance programs.

allenhiseadmose87.blogspot.com

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

0 Response to "How to Read Text Files From a Folder in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel