- How to Read Files in Java
- Reading Text Files in Java with BufferedReader
- Reading UTF-8 Encoded File in Java with BufferedReader
- Using Java Files Class to Read a File
- Reading Small Files in Java with Files Class
- Reading Large Files in Java with Files Class
- Reading Files with Files.lines()
- Reading Text Files in Java with Scanner
- Reading an Entire File
- Conclusion
- Java Read Files
- Example
- Get File Information
- Example
How to Read Files in Java
Throughout the tutorial, we are using a file stored in the src directory where the path to the file is src/file.txt .
Store several lines of text in this file before proceeding.
Note: You have to properly handle the errors when using these implementations to stick to the best coding practices.
Reading Text Files in Java with BufferedReader
The BufferedReader class reads a character-input stream. It buffers characters in a buffer with a default size of 8 KB to make the reading process more efficient. If you want to read a file line by line, using BufferedReader is a good choice.
BufferedReader is efficient in reading large files.
import java.io.*; public class FileReaderWithBufferedReader < public static void main(String[] args) throws IOExceptionbufferedReader.close(); > >
The readline() method returns null when the end of the file is reached.
Reading UTF-8 Encoded File in Java with BufferedReader
We can use the BufferedReader class to read a UTF-8 encoded file.
This time, we pass an InputStreamReader object when creating a BufferedReader instance.
import java.io.*; public class EncodedFileReaderWithBufferedReader < public static void main(String[] args) throws IOException < String file = "src/fileUtf8.txt"; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String curLine; while ((curLine = bufferedReader.readLine()) != null)< //process the line as you require System.out.println(curLine); >> >
Using Java Files Class to Read a File
Java Files class, introduced in Java 7 in Java NIO, consists fully of static methods that operate on files.
Using Files class, you can read the full content of a file into an array. This makes it a good choice for reading smaller files.
Let’s see how we can use Files class in both these scenarios.
Reading Small Files in Java with Files Class
The readAllLines() method of the Files class allows reading the whole content of the file and stores each line in an array as strings.
You can use the Path class to get the path to the file since the Files class accepts the Path object of the file.
import java.io.IOException; import java.nio.file.*; import java.util.*; public class SmallFileReaderWithFiles < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); Listlines = Files.readAllLines(path); > >
You can use readAllBytes() to retrieve the data stored in the file to a byte array instead of a string array.
byte[] bytes = Files.readAllBytes(path);
Reading Large Files in Java with Files Class
If you want to read a large file with the Files class, you can use the newBufferedReader() method to obtain an instance of BufferedReader class and read the file line by line using a BufferedReader .
import java.io.*; import java.nio.file.*; public class LargeFileReaderWithFiles < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); BufferedReader bufferedReader = Files.newBufferedReader(path); String curLine; while ((curLine = bufferedReader.readLine()) != null)< System.out.println(curLine); >bufferedReader.close(); > >
Reading Files with Files.lines()
Java 8 introduced a new method to the Files class to read the whole file into a Stream of strings.
import java.io.IOException; import java.nio.file.*; import java.util.stream.Stream; public class FileReaderWithFilesLines < public static void main(String[] args) throws IOException < String file = "src/file.txt"; Path path = Paths.get(file); Streamlines = Files.lines(path); lines.forEach(s -> System.out.println(s)); lines.close(); > >
Reading Text Files in Java with Scanner
The Scanner class breaks the content of a file into parts using a given delimiter and reads it part by part. This approach is best suited for reading content that is separated by a delimiter.
For example, the Scanner class is ideal for reading a list of integers separated by white spaces or a list of strings separated by commas.
The default delimiter of the Scanner class is whitespace. But you can set the delimiter to another character or a regular expression. It also has various next methods, such as next() , nextInt() , nextLine() , and nextByte() , to convert content into different types.
import java.io.IOException; import java.util.Scanner; import java.io.File; public class FileReaderWithScanner < public static void main(String[] args) throws IOException< String file = "src/file.txt"; Scanner scanner = new Scanner(new File(file)); scanner.useDelimiter(" "); while(scanner.hasNext())< String next = scanner.next(); System.out.println(next); >scanner.close(); > >
In the above example, we set the delimiter to whitespace and use the next() method to read the next part of the content separated by whitespace.
Reading an Entire File
You can use the Scanner class to read the entire file at once without running a loop. You have to pass “\\Z” as the delimiter for this.
scanner.useDelimiter("\\Z"); System.out.println(scanner.next()); scanner.close();
Conclusion
As you saw in this tutorial, Java offers many methods that you can choose from according to the nature of the task at your hand to read text files. 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 Read Files
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter:
Example
import java.io.File; // Import the File class import java.io.FileNotFoundException; // Import this class to handle errors import java.util.Scanner; // Import the Scanner class to read text files public class ReadFile < public static void main(String[] args) < try < File myObj = new File("filename.txt"); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) < String data = myReader.nextLine(); System.out.println(data); >myReader.close(); > catch (FileNotFoundException e) < System.out.println("An error occurred."); e.printStackTrace(); >> >
Get File Information
To get more information about a file, use any of the File methods:
Example
import java.io.File; // Import the File class public class GetFileInfo <
public static void main(String[] args) < File myObj = new File("filename.txt"); if (myObj.exists()) < System.out.println("File name: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable " + myObj.canRead()); System.out.println("File size in bytes " + myObj.length()); >else < System.out.println("The file does not exist."); >> >
File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
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. Which one to use depends on the Java version you’re working with and whether you need to read bytes or characters, and the size of the file/lines etc.
Tip: To delete a file, read our Java Delete Files chapter.