I'm interested in simple line processing.
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.
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.
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
Text Data. Whenever you want to handle text data, then you need to use the Reader / Writer classes.
Scanner:
for(Scanner sc = new Scanner(new File("my.file")); sc.hasNext(); ) {
String line = sc.nextLine();
... // do something with line
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With