How Can I Read a Text File in Java

At that place are many means to read a text file in java. Let's await at coffee read text file unlike methods one by one.

Java 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 nosotros can use Reader classes. There are some utility classes too to read a text file in coffee.

  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'southward look at examples showing how to read a text file in java using these classes.

Coffee 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 array. Files class also has a method to read all lines to a list of cord. Files class is introduced in Java seven and it'due south good if you lot desire to load all the file contents. You should use this method only when you lot are working on pocket-size files and y'all demand all the file contents in retentivity.

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

Read text file in java using java.io.FileReader

You lot can employ 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, and then information technology's not a very efficient manner of reading a text file in coffee.

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

Coffee read text file using java.io.BufferedReader

BufferedReader is good if you want to read file line by line and process on them. It's good for processing the large file and it supports encoding also.

BufferedReader is synchronized, then read operations on a BufferedReader can safely be washed 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()) != zip){      //procedure the line      System.out.println(line); } br.close();                      

Using scanner to read text file in coffee

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

Scanner breaks its input into tokens using a delimiter pattern, which past default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. The scanner form 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 past line while(scanner.hasNextLine()){     //process each line     String line = scanner.nextLine();     System.out.println(line); } scanner.close();                      

Coffee Read File Example

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

                          parcel com.journaldev.files;  import coffee.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import coffee.io.FileReader; import coffee.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import coffee.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(String[] args) throws IOException {         String fileName = "/Users/pankaj/source.txt";                  //using Coffee seven Files class to process 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 support, not efficient         readUsingFileReader(fileName);     }      individual static void readUsingFileReader(String fileName) throws IOException {         File file = new File(fileName);         FileReader fr = new FileReader(file);         BufferedReader br = new BufferedReader(fr);         String line;         System.out.println("Reading text file using FileReader");         while((line = br.readLine()) != null){             //process the line             System.out.println(line);         }         br.close();         fr.close();              }      individual 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;         Organization.out.println("Read text file using InputStreamReader");         while((line = br.readLine()) != null){             //process the line             Organisation.out.println(line);         }         br.close();              }      private static void readUsingBufferedReaderJava7(Cord 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 Coffee seven comeback");         while((line = br.readLine()) != null){             //process the line             Arrangement.out.println(line);         }         br.shut();     }      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()) != cipher){             //process the line             Organisation.out.println(line);         }         //close resources         br.shut();         fr.close();     }      private static void readUsingScanner(Cord fileName) throws IOException {         Path path = Paths.go(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();             Organization.out.println(line);         }         scanner.shut();     }      private static void readUsingFiles(String fileName) throws IOException {         Path path = Paths.get(fileName);         //read file to byte array         byte[] bytes = Files.readAllBytes(path);         System.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 case, if you are just logging the file, you can utilize Files and BufferedReader. If you lot are looking to parse the file based on a delimiter, yous should apply Scanner form.

Before I end this tutorial, I want to mention about RandomAccessFile. We tin use this to read text file in coffee.

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

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

porterhille1980.blogspot.com

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

0 Response to "How Can I Read a Text File in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel