Different ways of Reading a text file in Java

preview_player
Показать описание
Different ways of Reading a text file in Java:

1. Using BufferedReader class
2. Using FileReader class
3. Using Scanner class
4. Reading the whole file in a List
5. Read a text file as String

1. Using BufferedReader class:

Reads text from a character-input stream. It does buffer for efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.

BufferedReader in = new BufferedReader(Reader in, int size);

2. Using File Reader class:

Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.

1. FileReader(File file): Creates a new FileReader, given the File to read from

2. FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from

3. FileReader(String fileName): Creates a new FileReader, given the name of the file to read from

3. Using Scanner class:

A simple text scanner that can parse primitive types and strings using regular expressions. A 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 different types using the various next methods.

4. Reading the whole file in a List:

Read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.
Рекомендации по теме