Java Open and Read File Example and Close

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

Java read text file

java read file, java read text file

At that place are many ways to read a text file in java. A text file is made of characters, and then we tin employ Reader classes. There are some utility classes too to read a text file in java.

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

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

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

Nosotros can employ Files class to read all the contents of a file into a byte assortment. Files course also has a method to read all lines to a listing of string. Files course is introduced in Coffee vii and it's good if you desire to load all the file contents. Y'all should employ this method only when you are working on small files and yous need all the file contents in retentivity.

                          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 tin employ FileReader to get the BufferedReader and then read files line past line. FileReader doesn't support encoding and works with the organisation default encoding, so it's 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); String line; while((line = br.readLine()) != null){     //process the line     Organization.out.println(line); }                      

Java 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 information technology supports encoding also.

BufferedReader is synchronized, so read operations on a BufferedReader tin 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);  Cord line; while((line = br.readLine()) != naught){      //process the line      System.out.println(line); } br.shut();                      

Using scanner to read text file in java

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

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

                          Path path = Paths.go(fileName); Scanner scanner = new Scanner(path); Arrangement.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();                      

Java Read File Example

Here 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.

                          parcel com.journaldev.files;  import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import coffee.util.Listing; import coffee.util.Scanner;  public class JavaReadFile {      public static void main(String[] args) throws IOException {         String fileName = "/Users/pankaj/source.txt";                  //using Java 7 Files class to process pocket-sized files, get complete file data         readUsingFiles(fileName);                  //using Scanner course 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, non 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()) != zippo){             //process the line             System.out.println(line);         }         br.shut();         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;         Arrangement.out.println("Read text file using InputStreamReader");         while((line = br.readLine()) != nil){             //procedure the line             System.out.println(line);         }         br.close();              }      individual static void readUsingBufferedReaderJava7(Cord fileName, Charset cs) throws IOException {         Path path = Paths.get(fileName);         BufferedReader br = Files.newBufferedReader(path, cs);         String line;         System.out.println("Read text file using BufferedReader Coffee 7 improvement");         while((line = br.readLine()) != null){             //procedure 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()) != null){             //process the line             Arrangement.out.println(line);         }         //shut resources         br.close();         fr.shut();     }      private static void readUsingScanner(Cord fileName) throws IOException {         Path path = Paths.go(fileName);         Scanner scanner = new Scanner(path);         Organisation.out.println("Read text file using Scanner");         //read line past line         while(scanner.hasNextLine()){             //process each line             Cord line = scanner.nextLine();             System.out.println(line);         }         scanner.close();     }      private static void readUsingFiles(Cord 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 listing         @SuppressWarnings("unused") 		List<Cord> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);         System.out.println(new String(bytes));     }  }                      

The option 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 lot can use Files and BufferedReader. If you are looking to parse the file based on a delimiter, y'all should use Scanner class.

Earlier I stop this tutorial, I want to mention most RandomAccessFile. We tin utilize this to read text file in java.

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

That'southward all for java read text file example programs.

stevensuponat.blogspot.com

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

Belum ada Komentar untuk "Java Open and Read File Example and Close"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel