Read text file with java

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.

Читайте также:  Html meaning and definition

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.

Источник

Reading text files in Java

In Reading text files in Java tutorial we show how to read text files in Java. We use build-in tools including FileReader , InputStreamReader , and Scanner . In addition, we use API Google Guava library.

Google Guava is set of common libraries for Java; the set includes IO API, too.

The following examples use this text file.

The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.

The file is located in the src/resources/ directory.

Java read text classes

  • java.io.FileReader
  • java.nio.file.Files
  • java.util.Scanner
  • java.io.InputStreamReader
  • com.google.common.io.Files

Java read text file with FileReader

FileReader is a class used for reading character files. It reads text from character files using a default buffer size. Decoding from bytes to characters uses either a specified charset or the platform’s default charset.

Note: In the past, FileReader relied on the default platform’s encoding. Since Java 11, the issue was corrected. It is possible now to explicitly specify the encoding.

package com.zetcode; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; public class FileReaderEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; try (BufferedReader br = new BufferedReader( new FileReader(fileName, StandardCharsets.UTF_8))) < var sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) < sb.append(line); sb.append(System.lineSeparator()); >System.out.println(sb); > > >

The code example reads text from the thermopylae.txt file.

var fileName = "src/resources/thermopylae.txt";

In the fileName variable, we store the path to the file.

try (BufferedReader br = new BufferedReader( new FileReader(fileName, StandardCharsets.UTF_8))) 

The FileReader takes the file name as the first parameter. The second parameter is the charset used. The FileReader is passed to the BufferedReader , which buffers read operations for better performance. This is a try-with-resources statement which ensures that the resource (the buffered reader) is closed at the end of the statement.

var sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) < sb.append(line); sb.append(System.lineSeparator()); >System.out.println(sb);

Printing lines to the console consumes additional resources. Therefore, we use the StringBuilder to build the output string and print it in one operation. This is an optional optimization. The System.lineSeparator returns the system-dependent line separator string.

Java read text file with Files.readAllLines

The Files.readAllLines method reads all lines from a file. This method ensures that the file is closed when all bytes have been read or an exception is thrown. The bytes from the file are decoded into characters using the specified charset.

Note that this method reads the whole file into the memory; therefore, it may not be suitable for very large files.

package com.zetcode; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class ReadAllLinesEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; Listlines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); for (String line : lines) < System.out.println(line); >> >

The contents of the thermopylae.txt file are read and printed to the console using the Files.readAllLines method.

Reading text file with Java 8 streaming API

Another option to read text files is to use the Java 8 streaming API. The Files.lines reads all lines from a file as a stream. The bytes from the file are decoded into characters using the StandardCharsets.UTF-8 charset.

package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesLinesEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; Files.lines(Paths.get(fileName)).forEachOrdered(System.out::println); >>

The contents of the thermopylae.txt file are read and printed to the console using the Files.lines method.

Java read text file with Scanner

A Scanner is simple text scanner which can parse primitive types and strings using regular expressions.

package com.zetcode; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScannerEx < public static void main(String[] args) throws FileNotFoundException < var fileName = "src/resources/thermopylae.txt"; try (var scanner = new Scanner(new File(fileName))) < while (scanner.hasNext()) < String line = scanner.nextLine(); System.out.println(line); >> > >

The example reads a text file using a Scanner .

The file is read line by line with the nextLine method.

Java read text file with InputStreamReader

InputStreamReader is a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset.

package com.zetcode; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class InputStreamReaderEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; try (var br = new BufferedReader(new InputStreamReader( new FileInputStream(fileName), StandardCharsets.UTF_8))) < String line; while ((line = br.readLine()) != null) < System.out.println(line); >> > >

The example reads a text file using an InputStreamReader .

try (var br = new BufferedReader(new InputStreamReader( new FileInputStream(fileName), StandardCharsets.UTF_8))) 

The InputStreamReader is created from a FileInputStream , which creates an input stream by opening a connection to an actual file. The InputStreamReader is then passed to a BufferedReader for better efficiency.

Java 7 introduced a more convenient API to work with an InputStreamReader . A new buffered InputStreamReader can be created with Files.newBufferedReader .

package com.zetcode; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class InputStreamReaderEx2 < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; var filePath = Paths.get(fileName); try (BufferedReader br = Files.newBufferedReader( filePath, StandardCharsets.UTF_8)) < String line; while ((line = br.readLine()) != null) < System.out.println(line); >> > >

The example reads the thermopylae.txt file with the Files.newBufferedReader method.

Java read text file with Files.readAllBytes

The Files.readAllBytes method reads all the bytes from a file. It ensures that the file is closed when all bytes have been read.

package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ReadAllBytesEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; var filePath = Paths.get(fileName); byte[] data = Files.readAllBytes(filePath); var content = new String(data); System.out.println(content); >>

The example reads all bytes from a file and passes them to the String constructor.

Java read text with Files.readString

Java 11 introduces a convenient method that allows to read the whole file into a string in one shot.

The Files.readString reads all content from a file into a string, decoding from bytes to characters using the specified or the default (StandardCharsets.UTF_8) charset. It ensures that the file is closed when all content have been read.

package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ReadFileAsStringEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; var filePath = Paths.get(fileName); var content = Files.readString(filePath); System.out.println(content); >>

The example reads the contents of the thermopylae.txt file into a string a prints it to the terminal.

Java read text file with FileChannel

FileChannel is a channel for reading, writing, mapping, and manipulating a file. The advantages of file channels include reading and writing at a specific position of a file, loading a section of a file, or locking a section of a file.

package com.zetcode; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelEx < public static void main(String[] args) throws IOException < var fileName = "src/resources/thermopylae.txt"; try (RandomAccessFile myFile = new RandomAccessFile(fileName, "rw"); FileChannel inChannel = myFile.getChannel()) < ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) < buf.flip(); while (buf.hasRemaining()) < System.out.print((char) buf.get()); >buf.clear(); bytesRead = inChannel.read(buf); > > > >

The example reads the text file with FileChannel .

try (RandomAccessFile myFile = new RandomAccessFile(fileName, "rw"); FileChannel inChannel = myFile.getChannel()) 

A FileChannle is created from a RandomAccessFile .

ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf);

We allocate a buffer and read initial data.

while (bytesRead != -1) < buf.flip(); while (buf.hasRemaining()) < System.out.print((char) buf.get()); >buf.clear(); bytesRead = inChannel.read(buf); >

We read the data into the buffer and write it to the terminal. We use flip to change buffer from reading to writing.

Reading text file with Google Guava

Google Guava is a Java helper library which has IO tools, too. The following two Guava methods would consume a lot of system resources if the file to be read is very large.

  4.0.0 com.zetcode readtextguavaex 1.0-SNAPSHOT UTF-8 12 12   com.google.guava guava 28.0-jre    

This is the Maven POM file.

package com.zetcode; import com.google.common.base.Charsets; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.util.List; public class ReadTextGuavaEx < public static void main(String[] args) throws IOException < var fileName = "src/main/resources/thermopylae.txt"; Listlines = Files.readLines(new File(fileName), Charsets.UTF_8); var sb = new StringBuilder(); for (String line: lines) < sb.append(line); sb.append(System.lineSeparator()); >System.out.println(sb); > >

In the example, we read all of the lines from a file with the Files.readLines method. The method returns a list of strings. A default charset is specified as the second parameter.

In the second example, we use Files.asCharSource .

package com.zetcode; import com.google.common.base.Charsets; import com.google.common.io.Files; import java.io.File; import java.io.IOException; public class ReadTextGuavaEx2 < public static void main(String[] args) throws IOException < var fileName = "src/main/resources/thermopylae.txt"; var charSource = Files.asCharSource(new File(fileName), Charsets.UTF_8).read(); System.out.println(charSource); >>

The Files.asCharSource for reading character data from the given file using the given character set. Its read method reads the contents of this source as a string.

In this article we have read text files in various ways in Java.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Оцените статью