In this post, We will cover as How to read a file in Java. This post will cover different options available in Java to see how to read a file in Java.
JDK provides a number of option to read a file in Java, we will explore few of the options to read a file
Java 8 Provides an efficient way to read a file using Stream API. You can use Files.line to read it as a stream
File Content
This Show How
To Read File
Using Java 8
public class ReadFileByStream { public static void main(String[] args) { String fileName = "/tutorials/fileread/SampleFile.txt"; //this path is on my local try { List<String> readStream=Files.lines(Paths.get(fileName)).collect(Collectors.toList()); readStream.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } }
Output
This Show How To Read File Using Java 8
Java 8 Stream API is really clean and provide an elegant way to read the file.We have seen too many open files in a system exception being reported.
BufferReader with StringBuilder is an efficient way to read a small file in Java
public class ReadFileByBufferReader {
public static void main(String[] args){
String fileName = "/tutorials/fileread/SampleFile.txt";
try(BufferedReader bufferReader = new BufferedReader(new FileReader(fileName))) {
StringBuilder fileContent = new StringBuilder();
String line = bufferReader.readLine();
while (line != null) {
fileContent.append(line);
fileContent.append(System.lineSeparator());
line = bufferReader.readLine();
}
String fileInformation = fileContent.toString();
System.out.println(fileInformation);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
This Show How To Read File Using Buffer Reader
Above Example used the try-with-resources feature to autoclose stream.
package com.umeshawasthi.tutorials.corejava.io.readfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Created by umesh on 5/2/17.
*/
public class ReadFileByScanner {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "/tutorials/fileread/SampleFile.txt";
File inputFile = new File(fileName);
useScannerByLoop(inputFile);
useScannerWithoutLoop(inputFile);
}
private static void useScannerByLoop(final File file) throws FileNotFoundException {
Scanner fileScanner = new Scanner(file);
while(fileScanner.hasNextLine()){
System.out.println(fileScanner.nextLine());
}
fileScanner.close();
}
private static void useScannerWithoutLoop(final File file) throws FileNotFoundException {
Scanner fileScanner = new Scanner(file);
fileScanner.useDelimiter("\\Z");
System.out.println(fileScanner.next());
}
}
Output (For both cases)
This Show How To Read File Using Scanner With Loop
Make sure to check next line when using Scanner else it can throw NoSuchElementException exception
Apache Commons provides the convenient method to work with files.
Here is a clean and efficient way to as how to read a file in Java using Apache Commons IO Utils.
public class ReadFileByApacheIO {
public static void main(String[] args) throws IOException {
String fileName = "/tutorials/fileread/SampleFile.txt";
try(FileInputStream inputStream = new FileInputStream(fileName)){
String fileContent = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
System.out.println(fileContent);
}
}
}
Output
This Show How To Read File Using Apache IO
We have used Apache Commons IOUtils using Java 7 try-with-resources feature.
Apache FileUtils
public class ReadFileByApacheFileUtils {
public static void main(String[] args) throws IOException {
String fileName = "/Users/umesh/personal/tutorials/fileread/SampleFile.txt";
List<String> fileContent= FileUtils.readLines(new File(fileName), StandardCharsets.UTF_8);
for(String line : fileContent){
System.out.println(line);
}
}
}
Output
This Show How To Read File Using Apache IO
There are multiple ways as How to Read file in Java. All options have their own positive and negative.
Our recommendation is
If you are using Google Guava, you can use Guava in a very similar way Apache Commons IO.If you are working with very large files, please read How to Read Large File in Java
Please refer to our post on how to convert InputStream to String for a basic understanding of the process.
All the code of this article is available Over on Github. This is a Maven-based project.
References
Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.