Java — How to read a File | Code Factory
Donate : Link
WordPress Blog : Link
Learn how to read a text file or binary (image) file in Java using various classes and utility methods provided by Java like BufferedReader
, LineNumberReader
, Files.readAllLines
, Files.lines
, BufferedInputStream
, Files.readAllBytes
, etc.
Let’s look at each of the different ways of reading a file in Java with the help of examples.
Java read file using BufferedReader
BufferedReader is a simple and performant way of reading text files in Java. It reads text from a character-input stream. It buffers characters to provide efficient reading.
package com.example.java.programming.file;import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;/**
* @author code.factory
*
*/
public class BufferedReaderExample {
public static void main(String... args) {
Path filePath = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8; try (BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Output :
Hello
Code Factory!!!
Java read file line by line using Files.readAllLines()
Files.readAllLines() is a utility method of the Java NIO’s Files class that reads all the lines of a file and returns a List<String>
containing each line. It internally uses BufferedReader to read the file.
package com.example.java.programming.file;import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;/**
* @author code.factory
*
*/
public class FilesReadAllLinesExample {
public static void main(String... args) {
Path filePath = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;
try {
List<String> lines = Files.readAllLines(filePath, charset);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Output :
Hello
Code Factory!!!
Java read file line by line using Files.lines()
Files.lines() method reads all the lines from a file as a Stream
. You can use Stream API methods like forEach
, map
to work with each line of the file.
package com.example.java.programming.file;import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;/**
* @author code.factory
*
*/
public class FilesLinesExample {
public static void main(String... args) {
Path filePath = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8; try { Files.lines(filePath, charset).forEach(System.out::println); } catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Output :
Hello
Code Factory!!!
Java read file line by line using LineNumberReader
LineNumberReader is a buffered character-stream reader that keeps track of line numbers. You can use this class to read a text file line by line.
package com.example.java.programming.file;import java.io.BufferedReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;/**
* @author code.factory
*
*/
public class LineNumberReaderExample {
public static void main(String... args) {
Path filePath = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8; try (BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset);
LineNumberReader lineNumberReader = new LineNumberReader(bufferedReader)) { String line;
while ((line = lineNumberReader.readLine()) != null) {
System.out.format("Line %d: %s%n", lineNumberReader.getLineNumber(), line);
}
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Output :
Line 1: Hello
Line 2: Code Factory!!!
Java read binary file (image file) using BufferedInputStream
All the examples presented in this article so far read textual data from a character-input stream. If you’re reading a binary data such as an image file then you need to use a byte-input stream.
BufferedInputStream lets you read raw stream of bytes. It also buffers the input for improving performance.
package com.example.java.programming.file;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;/**
* @author code.factory
*
*/
public class BufferedInputStreamImageCopyExample {
public static void main(String... args) {
try (InputStream inputStream = Files.newInputStream(Paths.get("bike.jpg"));
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); OutputStream outputStream = Files.newOutputStream(Paths.get("bike-copy.jpg"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) { byte[] buffer = new byte[4096];
int numBytes;
while ((numBytes = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, numBytes);
}
System.out.println("Done");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Java read file into []byte using Files.readAllBytes()
If you want to read the entire contents of a file in a byte array then you can use the Files.readAllBytes() method.
package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;/**
* @author code.factory
*
*/
public class FilesReadAllBytesExample {
public static void main(String... args) {
try {
byte[] data = Files.readAllBytes(Paths.get("test.txt"));
System.out.println(new String(data));
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Output :
Hello
Code Factory!!!