Read file java windows

How to Read a File in Java

Last modified: January 30, 2021

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

If you have a few years of experience in the Java ecosystem, and you’re interested in sharing that experience with the community (and getting paid for your work of course), have a look at the «Write for Us» page. Cheers, Eugen

1. Overview

In this tutorial, we’ll explore different ways to read from a File in Java.

First, we’ll learn how to load a file from the classpath, a URL, or from a JAR file using standard Java classes.

Second, we’ll see how to read the content with BufferedReader, Scanner, StreamTokenizer, DataInputStream, SequenceInputStream, and FileChannel. We will also discuss how to read a UTF-8 encoded file.

Finally, we’ll explore the new techniques to load and read a file in Java 7 and Java 8.

This article is part of the “Java – Back to Basic” series on Baeldung.

Further reading:

Java – Create a File

Java – Write to File

2. Setup

2.1 Input File

In most examples throughout this article, we’ll read a text file with filename fileTest.txt that contains one line:

For a few examples, we’ll use a different file; in these cases, we’ll mention the file and its contents explicitly.

2.2 Helper Method

We’ll use a set of test examples with core Java classes only, and in the tests, we’ll use assertions with Hamcrest matchers.

Tests will share a common readFromInputStream method that transforms an InputStream to String for easier asserting of results:

Note that there are other ways of achieving this same result. We can consult this article for some alternatives.

3. Reading a File from the Classpath

3.1. Using Standard Java

This section explains how to read a file that is available on a classpath. We’ll read the “ fileTest.txt ” available under src/main/resources :

In the above code snippet, we used the current class to load a file using getResourceAsStream method and passed the absolute path of the file to load.

The same method is available on a ClassLoader instance as well:

We obtain the classLoader of the current class using getClass().getClassLoader() .

The main difference is that when using the getResourceAsStream on a ClassLoader instance, the path is treated as absolute starting from the root of the classpath.

When used against a Class instance , the path could be relative to the package, or an absolute path, which is hinted by the leading slash.

Of course, note that in practice, open streams should always be closed, such as the InputStream in our example:

3.2. Using the commons-io Library

Another common option is using the FileUtils class of the commons-io package:

Читайте также:  Using disk management in windows

Here we pass the File object to the method readFileToString() of FileUtils class. This utility class manages to load the content without the necessity of writing any boilerplate code to create an InputStream instance and read data.

The same library also offers the IOUtils class:

Here we pass the FileInputStream object to the method toString() of IOUtils class. This utility class acts in the same way as the previous one in order to create an InputStream instance and read data.

4. Reading with BufferedReader

Now let’s focus on different ways to parse the content of a file.

We’ll start with a simple way to read from a file using BufferedReader:

Note that readLine() will return null when the end of the file is reached.

5. Reading from a File Using Java NIO

In JDK7, the NIO package was significantly updated.

Let’s look at an example using the Files class and the readAllLines method. The readAllLines method accepts a Path.

Path class can be considered an upgrade of the java.io.File with some additional operations in place.

5.1. Reading a Small File

The following code shows how to read a small file using the new Files class:

Note that we can use the readAllBytes() method as well if we need binary data.

5.2. Reading a Large File

If we want to read a large file with Files class, we can use the BufferedReader.

The following code reads the file using the new Files class and BufferedReader:

5.3. Reading a File Using Files.lines()

JDK8 offers the lines() method inside the Files class. It returns a Stream of String elements.

Let’s look at an example of how to read data into bytes and decode it using UTF-8 charset.

The following code reads the file using the new Files.lines():

Using Stream with IO channels like file operations, we need to close the stream explicitly using the close() method.

As we can see, the Files API offers another easy way to read the file contents into a String.

In the next sections, we’ll look at other less common methods of reading a file that may be appropriate in some situations.

6. Reading with Scanner

Next let’s use a Scanner to read from the File. Here we’ll use whitespace as the delimiter:

Note that the default delimiter is the whitespace, but multiple delimiters can be used with a Scanner.

The Scanner class is useful when reading content from the console, or when the content contains primitive values, with a known delimiter (eg: a list of integers separated by space).

7. Reading with StreamTokenizer

Now let’s read a text file into tokens using a StreamTokenizer.

The tokenizer works by first figuring out what the next token is, String or number. We do that by looking at the tokenizer.ttype field.

Then we’ll read the actual token based on this type:

  • tokenizer.nval – if the type was a number
  • tokenizer.sval – if the type was a String

In this example, we’ll use a different input file which simply contains:

The following code reads from the file both the String and the number:

Note how the end of file token is used at the end.

This approach is useful for parsing an input stream into tokens.

8. Reading with DataInputStream

We can use DataInputStream to read binary or primitive data types from a file.

The following test reads the file using a DataInputStream:

9. Reading with FileChannel

If we are reading a large file, FileChannel can be faster than standard IO.

The following code reads data bytes from the file using FileChannel and RandomAccessFile:

10. Reading a UTF-8 Encoded File

Now let’s see how to read a UTF-8 encoded file using BufferedReader. In this example, we’ll read a file that contains Chinese characters:

11. Reading Content from URL

To read content from a URL, we will use “/” URL in our example:

Читайте также:  Windows 10 хочет обновиться

There are also alternative ways of connecting to a URL. Here we used the URL and URLConnection class available in the standard SDK.

12. Reading a File from a JAR

To read a file which is located inside a JAR file, we will need a JAR with a file inside it. For our example, we will read “LICENSE.txt” from the “hamcrest-library-1.3.jar” file:

Here we want to load LICENSE.txt that resides in Hamcrest library, so we will use the Matcher’s class that helps to get a resource. The same file can be loaded using the classloader too.

13. Conclusion

As we can see, there are many possibilities for loading a file and reading data from it using plain Java.

We can load a file from various locations like classpath, URL, or jar files.

Then we can use BufferedReader to read line by line, Scanner to read using different delimiters, StreamTokenizer to read a file into tokens, DataInputStream to read binary data and primitive data types, SequenceInput Stream to link multiple files into one stream, FileChannel to read faster from large files, etc.

We can find the source code for this article in the following GitHub repo .

How can I read a large text file line by line using Java?

I need to read a large text file of around 5-6 GB line by line using Java.

How can I do this quickly?

22 Answers 22

A common pattern is to use

You can read the data faster if you assume there is no character encoding. e.g. ASCII-7 but it won’t make much difference. It is highly likely that what you do with the data will take much longer.

EDIT: A less common pattern to use which avoids the scope of line leaking.

UPDATE: In Java 8 you can do

NOTE: You have to place the Stream in a try-with-resource block to ensure the #close method is called on it, otherwise the underlying file handle is never closed until GC does it much later.

3s? Mine seem to take minutes, with this «slow» way of reading. I am on an SSD so read speeds should not be a problem? – Jiew Meng Nov 8 ’13 at 0:06

Look at this blog:

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

Once Java 8 is out (March 2014) you’ll be able to use streams:

Printing all the lines in the file:

Here is a sample with full error handling and supporting charset specification for pre-Java 7. With Java 7 you can use try-with-resources syntax, which makes the code cleaner.

If you just want the default charset you can skip the InputStream and use FileReader.

Here is the Groovy version, with full error handling:

I documented and tested 10 different ways to read a file in Java and then ran them against each other by making them read in test files from 1KB to 1GB. Here are the fastest 3 file reading methods for reading a 1GB test file.

Note that when running the performance tests I didn’t output anything to the console since that would really slow down the test. I just wanted to test the raw reading speed.

Tested in Java 7, 8, 9. This was overall the fastest method. Reading a 1GB file was consistently just under 1 second.

This was tested successfully in Java 8 and 9 but it won’t work in Java 7 because of the lack of support for lambda expressions. It took about 3.5 seconds to read in a 1GB file which put it in second place as far as reading larger files.

Tested to work in Java 7, 8, 9. This took about 4.5 seconds to read in a 1GB test file.

You can find the complete rankings for all 10 file reading methods here.

Читайте также:  Changing dns in linux

How to Read Files in Java

Amir Ghahrai

Java provides several methods to read files. Each of these methods is appropriate for reading different types of files in different situations. Some are better for reading longer files, others are better for reading shorter ones, etc.

In this tutorial, we will be using the following Java classes to read files

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.

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.

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.

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.

You can use readAllBytes() to retrieve the data stored in the file to a byte array instead of a string array.

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 .

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.

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.

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.

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.

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