10 Examples To Read A Text File Inward Java

10 Examples To Read A Text File Inward Java - Hallo sahabat BEST LEARNING JAVA, Pada Artikel yang anda baca kali ini dengan judul 10 Examples To Read A Text File Inward Java, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel Java File Tutorial, Artikel java IO tutorial, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : 10 Examples To Read A Text File Inward Java
link : 10 Examples To Read A Text File Inward Java

Baca juga


10 Examples To Read A Text File Inward Java

The Java IO API provides ii kinds of interfaces for reading files, streams together with readers. The streams are used to read binary information together with readers to read graphic symbol data. Since a text file is total of characters, y'all should live using a Reader implementations to read it. There are several ways to read a evidently text file inward Java e.g. y'all tin forcefulness out occupation FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of information for fast reading, together with Scanner provides parsing ability. You tin forcefulness out also occupation both BufferedReader together with Scanner to read a text file occupation yesteryear line inward Java. Then Java SE 8 introduces approximately other Stream shape java.util.stream.Stream which provides a lazy together with to a greater extent than efficient means to read a file.

The JDK seven also introduces a yoke of squeamish utility e.g. Files shape together with try-with-resource build which made reading a text file, fifty-fifty more, easier.

In this article, I am going to portion a yoke of examples of reading a text file inward Java alongside their pros, cons, together with of import points well-nigh each approach. This volition hand y'all plenty exceptional to pick out the correct tool for the task depending on the size of file, content of the file together with how y'all desire to read.



Reading a text file using FileReader

The FileReader is your full general purpose Reader implementation to read a file. It accepts a String path to file or a java.io.File instance to start reading. It also provides a yoke of overloaded read() methods to read a character, or read characters into an array or into a CharBuffer object. Here is an representative of reading a text file using FileReader inward Java:

public static void readTextFileUsingFileReader(String fileName) {     try {       FileReader textFileReader = new FileReader(fileName);       char[] buffer = new char[8096];       int numberOfCharsRead = textFileReader.read(buffer);       while (numberOfCharsRead != -1) {         System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead = textFileReader.read(buffer);       }       textFileReader.close();     } catch (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }   }  Output Once upon a time, nosotros wrote a programme to read data from a text file. The programme failed to read a large file but thus Java 8 come upwards to rescue, which made reading file lazily using Streams. 

You tin forcefulness out run across that instead of reading 1 graphic symbol at a time, I am reading characters into an array. This is to a greater extent than efficient because read() volition access the file several times but read(char[]) volition access the file exactly 1 fourth dimension to read the same amount of data.

I am using an 8KB of the buffer, thus inward 1 telephone band I am limited to read that much information only. You tin forcefulness out receive got a bigger or smaller buffer depending upon your heap memory together with file size. You should also notice that I am looping until read(char[]) returns -1 which signal the goal of the file.

Another interesting affair to regime annotation is to telephone band to String.valueOf(buffer, 0, numberOfCharsRead), which is required because y'all mightiness non receive got 8KB of information inward the file or fifty-fifty alongside a bigger file, the in conclusion telephone band may non able to fill upwards the char array together with it could incorporate dingy information from the in conclusion read.





Reading a text file inward Java using BufferedReader

The BufferedReader shape is a Decorator which provides buffering functionality to FileReader or whatever other Reader. This shape buffer input from source e.g. files into retentivity for efficient read. In the instance of BufferedReader, the telephone band to read() doesn't ever goes to file if it tin forcefulness out notice the information inward the internal buffer of BufferedReader.

The default size of the internal buffer is 8KB which is adept plenty for the most purpose, but y'all tin forcefulness out also increase or decrease buffer size piece creating BufferedReader object. The reading code is like to the previous example.

public static void readTextFileUsingBufferdReader(String fileName) {     try {       FileReader textFileReader = new FileReader(fileName);       BufferedReader bufReader = new BufferedReader(textFileReader);        char[] buffer = new char[8096];        int numberOfCharsRead = bufReader.read(buffer); // read volition live from       // memory       while (numberOfCharsRead != -1) {         System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead = textFileReader.read(buffer);       }        bufReader.close();      } catch (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }   }  Output [From File] Java provides several ways to read file

In this representative every bit well, I am reading the content of the file into an array. Instead of reading 1 graphic symbol at a time, this is to a greater extent than efficient. The alone departure betwixt the previous examples together with this 1 is that the read() method of BufferedReader is faster than read() method of FileReader because read tin forcefulness out come about from retentivity itself.

In lodge to read the full-text file, y'all loop until read(char[]) method returns -1, which signals the goal of the file. See Core Java Volume 1 - Fundamentals to acquire to a greater extent than well-nigh how BufferedReader shape industrial plant inward Java.

 The Java IO API provides ii kinds of interfaces for reading files 10 Examples to read a text file inward Java




Reading a text file inward Java using Scanner

The tertiary tool or shape to read a text file inward Java is the Scanner, which was added on JDK 1.5 release. The other ii FileReader together with BufferedReader are nowadays from JDK 1.0 together with JDK 1.1 version. The Scanner is much to a greater extent than characteristic rich together with versatile class. It does non exactly render reading but parsing of information every bit well. You tin forcefulness out non alone read text information but y'all tin forcefulness out also read text every bit number or float using nextInt() together with nextFloat() methods.

The shape uses regular facial expression pattern to create upwards one's hear token, which could live tricky for newcomers. The ii principal method to read text information from Scanner is next() together with nextLine(), erstwhile 1 read words separated yesteryear infinite piece afterwards 1 tin forcefulness out live used to read a text file occupation yesteryear occupation inward Java. In most cases, y'all would occupation the nextLine() method every bit shown below:

public static void readTextFileUsingScanner(String fileName) {     try {       Scanner sc = new Scanner(new File(fileName));       while (sc.hasNext()) {         String str = sc.nextLine();         System.out.println(str);       }       sc.close();     } catch (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }   } Output [From File] Java provides several ways to read the file.

You tin forcefulness out occupation the hasNext() method to create upwards one's hear if at that spot is whatever to a greater extent than token left to read inward the file together with loop until it returns false. Though y'all should yell back that next() or nextLine() may block until information is available fifty-fifty if hasNext() render true. This code is reading the content of "file.txt" occupation yesteryear line. See this tutorial to acquire to a greater extent than well-nigh Scanner shape together with file reading inward Java.




Reading a text file using Stream inward Java 8

The JDK 8 unloose has brought approximately cool novel features e.g. lambda expression together with streams which brand file reading fifty-fifty smoother inward Java. Since streams are lazy, y'all tin forcefulness out occupation them to read alone lines y'all desire from the file e.g. y'all tin forcefulness out read all non-empty lines yesteryear filtering empty lines. The occupation of method reference also makes the file reading code much to a greater extent than uncomplicated together with concise, thus much thus that y'all tin forcefulness out read a file inward exactly 1 occupation every bit shown below:

Files.lines(Paths.get("newfile.txt")).forEach(System.out::println);  Output This is the first occupation of file  something is improve than nix  this is the last occupation of the file

Now, if y'all desire to practise approximately pre-processing, hither is code to cut back each line, filter empty lines to alone read non-empty ones, together with remember, this is lazy because Files.lines() method render a current of String together with Streams are lazy inward JDK 8 (see Java 8 inward Action).

Files.lines(new File("newfile.txt").toPath()) .map(s -> s.trim())  .filter(s -> !s.isEmpty())  .forEach(System.out::println); 


We'll occupation this code to read a file which contains a occupation which is total of whitespace together with an empty line, the same 1 which nosotros receive got used inward the previous example, but this time, output volition non incorporate 5 occupation but exactly 3 lines because empty lines are already filtered, every bit shown below:

Output This is the first occupation of file something is improve than nix this is the last occupation of the file

You tin forcefulness out run across alone 3 out of 5 lines appeared because other ii got filtered. This is exactly tip of the iceberg on what y'all tin forcefulness out practise alongside Java SE 8, See Java SE 8 for Really Impatient  to acquire to a greater extent than well-nigh Java 8 features.

 The Java IO API provides ii kinds of interfaces for reading files 10 Examples to read a text file inward Java



How to read a text file every bit String inward Java

Sometimes y'all to read the total content of a text file every bit String inward Java. This is to a greater extent than frequently than non the instance alongside pocket-size text files every bit for large file y'all volition human face upwards java.lang.OutOfMemoryError: coffee heap space error. Prior to Java 7, this requires a lot of boiler code because y'all demand to occupation a BufferedReader to read a text file occupation yesteryear occupation together with thus add together all those lines into a StringBuilder together with finally render the String generated from that.

Now y'all don't demand to practise all that, y'all tin forcefulness out occupation the Files.readAllBytes() method to read all bytes of the file inward 1 shot. Once done that y'all tin forcefulness out convert that byte array into String. every bit shown inward the next example:

public static String readFileAsString(String fileName) {     String data = "";     try {       data = new String(Files.readAllBytes(Paths.get("file.txt")));     } catch (IOException e) {       e.printStackTrace();     }      return data;   } Output [From File] Java provides several ways to read file

This was a rather pocket-size file thus it was pretty easy. Though, piece using readAllBytes() y'all should yell back graphic symbol encoding. If your file is non inward platform's default graphic symbol encoding thus y'all must specify the graphic symbol doing explicitly both piece reading together with converting to String. Use the overloaded version of readAllBytes() which accepts graphic symbol encoding. You tin forcefulness out also run across how I read XML every bit String inward Java here.




Reading the whole file inward a List

Similar to the in conclusion example, sometimes y'all demand all lines of the text file into an ArrayList or Vector or only on a List. Prior to Java 7, this task also involves boilerplate e.g. reading file occupation yesteryear line, adding them into a listing together with finally returning the listing to the caller, but after Java 7, it's really uncomplicated now. You exactly demand to occupation the Files.readAllLines() method, which render all lines of the text file into a List, every bit shown below:

public static List<String> readFileInList(String fileName) {     List<String> lines = Collections.emptyList();     try {       lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     } catch (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }     return lines; }

Similar to the in conclusion example, y'all should specify graphic symbol encoding if it's dissimilar than platform's default encoding. You tin forcefulness out occupation run across I receive got specified UTF-8 here. Again, occupation this fox alone if y'all know that file is pocket-size together with y'all receive got plenty retentivity to concord a List containing all occupation of the text file, otherwise your Java programme volition crash alongside OutOfMemoryError.

 The Java IO API provides ii kinds of interfaces for reading files 10 Examples to read a text file inward Java




How to read a text file inward Java into an array

This representative is also really like to in conclusion ii example, this time, nosotros are reading contents of the file into a String array. I receive got used a shortcut here, first, I receive got read all the lines every bit List together with thus converted the listing to array. This number inward uncomplicated together with elegant code, but y'all tin forcefulness out also read information into graphic symbol array every bit shown inward the root example. Use the read(char[] data) method piece reading information into a graphic symbol array.

Here is an representative of reading a text file into String array inward Java:

public static String[] readFileIntoArray(String fileName) {     List<String> list = readFileInList(fileName);     return list.toArray(new String[list.size()]); }

This method leverage our existing method which read the file into a List together with the code hither is alone to convert a listing to array inward Java.



How to read a file occupation yesteryear occupation inward Java

This is 1 of the interesting examples of reading a text file inward Java. You frequently demand file information every bit occupation yesteryear line. Fortunately, both BufferedReader together with Scanner provides convenient utility method to read occupation yesteryear line. If y'all are using BufferedReader thus y'all tin forcefulness out occupation readLine() together with if y'all are using Scanner thus y'all tin forcefulness out occupation nextLine() to read file contents occupation yesteryear line. In our example, I receive got used BufferedReader every bit shown below:

public static void readFileLineByLine(String fileName) {     try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {       String occupation = br.readLine();       while (line != null) {         System.out.println(line);         occupation = br.readLine();       }     } catch (IOException e) {       e.printStackTrace();     }   }

Just yell back that Influenza A virus subtype H5N1 occupation is considered to live terminated yesteryear whatever 1 of a occupation feed ('\n'), a railroad vehicle render ('\r'), or a railroad vehicle render followed straightaway yesteryear a linefeed.

 The Java IO API provides ii kinds of interfaces for reading files 10 Examples to read a text file inward Java


Java Program to read a text file inward Java

Here is the consummate Java programme to read a evidently text file inward Java. You tin forcefulness out run this programme inward Eclipse provided y'all create the files used inward this programme e.g. "sample.txt", "file.txt", together with "newfile.txt". Since I am using a relative path, y'all must ensure that files are inward the classpath. If y'all are running this programme inward Eclipse, y'all tin forcefulness out exactly create these files inward the root of the projection directory. The programme volition throw FileNotFoundException or NoSuchFileExcpetion if it is non able to notice the files.

import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Scanner;  /*  * Java Program read a text file inward multiple way.  * This programme demonstrate how y'all tin forcefulness out occupation FileReader,  * BufferedReader, together with Scanner to read text file,  * along alongside newer utility methods added inward JDK seven  * together with 8.   */  public class FileReadingDemo {    public static void main(String[] args) throws Exception {      // Example 1 - reading a text file using FileReader inward Java     readTextFileUsingFileReader("sample.txt");          // Example 2 - reading a text file inward Java using BufferedReader     readTextFileUsingBufferdReader("file.txt");          // Example 3 - reading a text file inward Java using Scanner     readTextFileUsingScanner("file.txt");          // Example iv - reading a text file using Stream inward Java 8     Files.lines(Paths.get("newfile.txt")).forEach(System.out::println);              // Example 5 - filtering empty lines from a file inward Java 8     Files.lines(new File("newfile.txt").toPath())     .map(s -> s.trim())      .filter(s -> !s.isEmpty())      .forEach(System.out::println);               // Example half dozen - reading a text file every bit String inward Java     readFileAsString("file.txt");               // Example seven - reading whole file inward a List     List<String> lines = readFileInList("newfile.txt");     System.out.println("Total number of lines inward file: " + lines.size());          // Example 8 - how to read a text file inward coffee into an array     String[] arrayOfString = readFileIntoArray("newFile.txt");     for(String line: arrayOfString){     System.out.println(line);     }          // Example nine - how to read a text file inward coffee occupation yesteryear line     readFileLineByLine("newFile.txt");          // Example 10 - how to read a text file inward java using eclipse     // all examples y'all tin forcefulness out run inward Eclipse, at that spot is nix special well-nigh it.         }    public static void readTextFileUsingFileReader(String fileName) {     try {       FileReader textFileReader = new FileReader(fileName);       char[] buffer = new char[8096];       int numberOfCharsRead = textFileReader.read(buffer);       while (numberOfCharsRead != -1) {         System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead = textFileReader.read(buffer);       }       textFileReader.close();     } catch (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }   }    public static void readTextFileUsingBufferdReader(String fileName) {     try {       FileReader textFileReader = new FileReader(fileName);       BufferedReader bufReader = new BufferedReader(textFileReader);        char[] buffer = new char[8096];        int numberOfCharsRead = bufReader.read(buffer); // read volition live from       // memory       while (numberOfCharsRead != -1) {         System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead = textFileReader.read(buffer);       }        bufReader.close();      } catch (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }   }    public static void readTextFileUsingScanner(String fileName) {     try {       Scanner sc = new Scanner(new File(fileName));       while (sc.hasNext()) {         String str = sc.nextLine();         System.out.println(str);       }       sc.close();     } catch (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }   }    public static String readFileAsString(String fileName) {     String data = "";     try {       data = new String(Files.readAllBytes(Paths.get("file.txt")));     } catch (IOException e) {       e.printStackTrace();     }      return data;   }    public static List<String> readFileInList(String fileName) {     List<String> lines = Collections.emptyList();     try {       lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     } catch (IOException e) {       // TODO Auto-generated grab block       e.printStackTrace();     }     return lines;   }    public static String[] readFileIntoArray(String fileName) {     List<String> list = readFileInList(fileName);     return list.toArray(new String[list.size()]);    }    public static void readFileLineByLine(String fileName) {     try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {       String occupation = br.readLine();       while (line != null) {         System.out.println(line);         occupation = br.readLine();       }     } catch (IOException e) {       e.printStackTrace();     }   } }

I receive got non printed the output hither because nosotros receive got already gone through that together with hash out inward respective examples, but y'all demand Java 8 to compile together with run this program. If y'all are running on Java 7, thus exactly take the representative iv together with 5 which uses Java 8 syntax together with features together with the programme should run fine.


That's all well-nigh how to read a text file inward Java. We receive got looked at all major utilities together with classes which y'all tin forcefulness out occupation to read a file inward Java e.g. FileReader, BufferedReader, together with Scanner. We receive got also looked at utility methods added on Java NIO 2 on JDK seven e.g. Files.readAllLines() together with Files.readAllBytes() to read the file inward List together with String respectively. Finally, nosotros receive got also touched novel means of file reading alongside Java 8 Stream, which provides lazy reading together with the useful pre-processing alternative to filter unnecessary lines.

Further Learning
Complete Java Masterclass
solution)
  • How to read an XML file inward Java? (guide)
  • How to read an Excel file inward Java? (guide)
  • How to read an XML file every bit String inward Java? (example)
  • How to re-create non-empty directory inward Java? (example)
  • How to read/write from/to RandomAccessFile inward Java? (tutorial)
  • How to append text to a File inward Java? (solution)
  • How to read a ZIP file inward Java? (tutorial)
  • How to read from a Memory Mapped file inward Java? (example)



  • Demikianlah Artikel 10 Examples To Read A Text File Inward Java

    Sekianlah artikel 10 Examples To Read A Text File Inward Java kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

    Anda sekarang membaca artikel 10 Examples To Read A Text File Inward Java dengan alamat link https://bestlearningjava.blogspot.com/2020/03/10-examples-to-read-text-file-inward.html

    Belum ada Komentar untuk "10 Examples To Read A Text File Inward Java"

    Posting Komentar

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel