Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (1.3k points)

It seems there are different ways to read and write data of files in Java.

I want to read ASCII data from a file. What are the possible ways and their differences?

1 Answer

0 votes
by (13.2k points)

There are many ways you can do this, as ASCII is a text file these are the following ways you can use -

  1. BufferedReader

The most common method to read a text file in Java is BufferedReader. It is really efficient for reading large text files.The buffer size may be specified, or the default size may be used. Usually, the default value is large enough for most files.

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

  1. Scanner

This is another method used for large files.It is a  simple text scanner and can parse primitive types and strings using regular expressions.

Scanner in = new Scanner( Reader in );

  1. Java nio

In JDK 7, nio package was introduced which can be used to store a whole plain text file into a List<String> using Files.readAllLines().This method closes the file when all bytes have been read or there is an I/O error or any other runtime exception is thrown.

It cannot be used for large files as this method loads the whole file in memory all at once.

 List<String> lines = Files.readAllLines(filePath);

  1. Java 8

For Java 8, there is a simple one liner to store the contents of a text file to List<String>.

 List<String> lines = Files.lines(path).collect(Collectors.toList());

Related questions

0 votes
1 answer
asked Jul 9, 2019 in Java by Nigam (4k points)
0 votes
1 answer
asked Jul 9, 2019 in Java by prachi95 (1.1k points)
0 votes
1 answer
asked Jul 10, 2019 in Java by tara92 (920 points)
0 votes
1 answer
asked Oct 13, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
asked Sep 29, 2019 in Java by Shubham (3.9k points)

Browse Categories

...