Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best/simplest classes used for reading files in Java?

Tags:

java

file

file-io

I'm interested in simple line processing.

like image 478
John Assymptoth Avatar asked Feb 05 '11 19:02

John Assymptoth


People also ask

Which class can be used for reading files in Java?

Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream , etc.

What is the best way to read a file in Java?

You can use BufferedReader to read large files line by line. If you want to read a file that has its content separated by a delimiter, use the Scanner class. Also you can use Java NIO Files class to read both small and large files.

Which class is used to read files?

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.

Which Java class is the preferred class for reading from a text file?

Text Data. Whenever you want to handle text data, then you need to use the Reader / Writer classes.


2 Answers

Scanner:

for(Scanner sc = new Scanner(new File("my.file")); sc.hasNext(); ) {
  String line = sc.nextLine();
  ... // do something with line
}
like image 77
Itay Maman Avatar answered Oct 05 '22 23:10

Itay Maman


Take a look at the Scanner class.

It was added in Java 5 to make reading strings and files far easier, than the old FileReaders and FileInputStream chains (no more new BufferedReader(new FileReader()) just to get to a readLine method).

In the Scanner class, you can use the nextLine method to read a line at a time, but it also has lots of util methods for finding primitives and regular expressions in the file.

like image 34
Codemwnci Avatar answered Oct 06 '22 01:10

Codemwnci