In this post, We will cover as the different option to read a file with Java. We will explore following options to read a file.
- BufferReader.
- FileChannel
- DataInputStream
- Scanner
- StreamTokenizer
We will also look in to the new way to read from a file in Java 7. At the end of this article, we will explore the new stream API in Java 8 to read a file.
1. Read with BufferReader
The BufferReader is the most common and simple way to read a file with Java. Before we start, I am creating a file name “read_java_file.txt
” and place it under the src/main/resources
(You can read a file from other location as well). Here is a simple code to read files in Java using BufferReader:
private final String FILE_LOCATION = "src/main/resources/read_java_file.txt";
public void readFileUsingBufferReader() throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(FILE_LOCATION));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// perform your logic with the data
System.out.println(line);
}
}
The readLine()
method return NULL when reached at the end of the file
2. Read File Using FileChannel
The FileChannel is a good option to read large files in Java.
public void readFileUsingFileChannel() throws IOException {
// open filechannel
RandomAccessFile file = new RandomAccessFile(FILE_LOCATION, "r");;
FileChannel channel = file.getChannel();
//set the buffer size
int bufferSize = 1024;
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
// read the data from filechannel
while (channel.read(buffer) != -1) {
System.out.println(new String(buffer.array()));
}
// clode both channel and file
channel.close();
file.close();
}
To work with FileChannel, keep in mind the following sequence:
- Open the file FileChannel.
- Set the buffer size.
- Read file data from the FileChannel.
3. DataInputStream
If the file contains binary or primitive data, DataInputStream might be a good choice for us.Let’s see how to read file using DataInputStream
.
public void readFileUsingDataInputStream() throws IOException {
DataInputStream dataInputStream = new DataInputStream(new FileInputStream(FILE_LOCATION));
while (dataInputStream.available() > 0) {
System.out.println(dataInputStream.readUTF());
}
dataInputStream.close();
}
4. Read File Using Scanner
Another way to read a file with Java is through Scanner.
private final String FILE_LOCATION = "src/main/resources/read_java_file.txt";
public void readFileUsingScanner() throws IOException {
// init scanner and provide file location
Scanner scanner = new Scanner(new File(FILE_LOCATION),StandardCharsets.UTF_8.name());
// set the delimiter.We want to read entire line in one go.You can set as per your requirement
scanner.useDelimiter("\\n");
// hasNext to check if there are any more data and next to read the entire line
while(scanner.hasNext()){
// perform your logic with the data
System.out.println(scanner.next());
}
}
}
5. Read File Using StreamTokenizer
The Java StreamTokenizer class tokenize the data into tokens. Let’s take a simple example of “Hello World”, each word in StreamTokenizer is a separate token. The StreamTokenizer class provides several options to read different type of data. Let’s look at some important fields:
- sval – If the token is String. This field provides String value for the token.
- nval – Number value for the token.
- ttype – The type of token read (word, number, end of line)
For this example, we will create a new file with following data:
Currently, the US has 50 states as well as 1 federal district
Of these 50 states, 48 of them are contiguous, that is, they are connected directly.
private final String STREAMTOKENIZER_FILE_LOCATION = "src/main/resources/stream_tokenizer_read_java_file.txt";
public void readFileStreamTokenizer() throws IOException {
// init the file and StreamTokenizer
FileReader reader = new FileReader(STREAMTOKENIZER_FILE_LOCATION);
StreamTokenizer tokenizer = new StreamTokenizer(reader);
// we will iterate through the output until end of file
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
// we will work on the data based on the data type
if (tokenizer.ttype == StreamTokenizer.TT_WORD) {
System.out.println(tokenizer.sval);
} else if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
System.out.println(tokenizer.nval);
} else if (tokenizer.ttype == StreamTokenizer.TT_EOL) {
System.out.println();
}
}
}
6. Read UTF-8 File
Not all files are simple enough especially when we are working on the multilingual applications. Let’s see how to read a file which contains the special characters. This is how our file will look like:
目前,美国有50个州以及1个联邦区
在这50个州中,有48个是连续的,也就是说,它们是直接连接的
Let’s see how to read this file using UTF-8 encoding
private final String UTF8_FILE_LOCATION = "src/main/resources/special_char_data.txt";
public void readUTF8FileData() throws IOException {
// create a Buffer reader without encoding and pass encoding information
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(UTF8_FILE_LOCATION)));
String line;
// we iterate until EOF
while ((line = bufferedReader.readLine()) != null) {
// perform your logic with the data
System.out.println(line);
}
// close the buffer
bufferedReader.close();
}
7. Read File using BufferReader and StringBuilder
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 = "src/main/resources/read_java_file.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();
}
}
}
Above Example used the try-with-resources feature to auto-close stream.
Output
This Show How
To Read File
Using Buffer Reader
8. Read File With Java 7
Java 7 came with several changes to the way we read and write file (especially the NIO). The first option is to use the readAllBytes() method. It reads all the bytes from the file. This will ensure to close the file when all bytes have been read, or it throws I/O error. Let’s see how to use this option:
package com.javadevjournal.read.file;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadDataWithJava7 {
private static final String FILE_LOCATION = "src/main/resources/read_java_file.txt";
public static void main(String[] args) {
String output = readFileReadAllBytes(FILE_LOCATION);
System.out.println(output);
}
/*
Internal method to read the data from the file using readAllBytes method
*/
private static String readFileReadAllBytes(final String path) {
// define a data holder to store the data read from the file
String data = "";
try {
data = new String(Files.readAllBytes(Paths.get(path)));
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}<code>
8.1 Using Buffer Reader
We can also combine the Files class with the BufferReader. This can be helpful if you reading large files:
package com.javadevjournal.read.file;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadDataWithJava7 {
private static final String FILE_LOCATION = "src/main/resources/read_java_file.txt";
public static void main(String[] args) {
output = readFileBufferReader(FILE_LOCATION);
System.out.println(output);
}
/*
Read files using the new Files class and BufferReader option
*/
private static String readFileBufferReader(final String filePath) {
// define a data holder to store the data read from the file
Path path = Paths.get(filePath);
StringBuilder fileContent = new StringBuilder();
try {
BufferedReader br = Files.newBufferedReader(path);
String line;
while ((line = br.readLine()) != null) {
// perform your logic with the data
fileContent.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return fileContent.toString();
}
}
9. Read Java File With Java 8
Java 8 provides some interesting features which includes the stream API.Let’s see how to use the Java 8 stream API to read file efficiently:
package com.javadevjournal.read.file;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ReadFileUsingJava8 {
private static final String FILE_LOCATION = "src/main/resources/read_java_file.txt";
public static void main(String[] args) throws IOException {
readLineByLine(FILE_LOCATION);
readWithBuilder(FILE_LOCATION);
}
/*
This method read the file line by line using Java 8 stream API
*/
private static void readLineByLine(final String fileLocation) throws IOException {
// create the path
Path path = Paths.get(fileLocation);
try (Stream < String > stream = Files.lines(path)) {
// read one line ar a time
stream.forEach(System.out::println);
}
}
/*
Read all content line by line but add them to a StringBuilder
*/
private static void readWithBuilder(final String fileLocation) throws IOException {
StringBuilder sb = new StringBuilder();
// create the path
Path path = Paths.get(fileLocation);
try (Stream < String > stream = Files.lines(path)) {
// read one line ar a time
stream.forEach(s - > sb.append(s).append("/n"));
}
System.out.println(sb.toString());
}
}
10. Apache Commons IO Utils
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
10.1 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
Summary
In this post, we see the different option to read a file. We have the option to use BufferedReader to read line by line or use a scanner to read a file with Java. We also look at the new API with Java 7 which provides a more powerful and clean approach to read a file. In the end of this article, we discussed how to use the new Stream API to read a file in Java 8. The source code for this article is available on the GitHub.
Comments are closed.