java tutorial - How to Reading a Plain Text File in Java - java programming - learn java - java basics - java for beginners



Reading a Plain Text File in Java:

  • There are several ways to read a plain text file in Java. FileReader, BufferedReader or Scanner to read a text file.
  • Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
  • We use BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream it provides a lazy and more efficient way to read a file.
  • Several ways of reading files. they are:

Using BufferedReader:

  • This method reads text from a character-input stream. It does buffering for efficient reading of characters, arrays, and lines.
  • The buffer size may be specified, or the default size may be used.
  • Each read request to be made of the underlying character. It is advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders.
  • For example,
BufferedReader in = new BufferedReader(Reader in, int size);

Using FileReader class:

  • Java FileReader class is used to read data from the file. It returns data in byte format.
  • This class accept that the default character encoding and the default byte-buffer size are appropriate.
  • Constructors defined in this class are:
// Creates a new FileReader, given the
// File to read from.
FileReader(File file)
// Creates a new FileReader, given the
// FileDescriptor to read from.
FileReader(FileDescriptor fd)
// Creates a new FileReader, given the
// name of the file to read from.
FileReader(String fileName)

Using Scanner class:

  • The java.util.Scanner is used to read file line by line in Java. We have first created a File instance in Java and then we passed this File instance to java.util.Scanner for scanning.
  • Scanner provides methods like NextLine() and readNextLine() which can be used to read file line by line.

Related Searches to How to Reading a Plain Text File in Java