How to read from file java

How to read from file java

Different ways of Reading a text file in Java

There are multiple ways of writing and reading a text file. this is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.

Methods:

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

We can also use both BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.

Tip Note: Practices of writing good code like flushing/closing streams, Exception-Handling etc, have been avoided for better understanding of codes by beginners as well.

Let us discuss each of the above methods to a deeper depth and most importantly by implementing them via a clean java program.

This method reads text from a character-input stream. It does buffer for efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders as shown below as follows:

How to Read Files in Java

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file 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

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

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.

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.

Java: How to read a text file

I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?

Here is an example of contents of the text file:

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

9 Answers 9

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You can use String#split() to split a String in parts based on a regular expression.

So, in a nutshell (assuming that the file doesn’t have empty lines nor trailing/leading whitespace).

Java 1.5 introduced the Scanner class for handling input from file and streams.

It is used for getting integers from a file and would look something like this:

Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

This example code shows you how to read file in Java.

Look at this example, and try to do your own:

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

Just for fun, here’s what I’d probably do in a real project, where I’m already using all my favourite libraries (in this case Guava, formerly known as Google Collections).

Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible’s Scanner solution doesn’t have any more code!

Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you’d be silly not to make use of Guava in your projects. 😉

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

Use Apache Commons (IO and Lang) for simple/common things like this.

Using Java 7 to read files with NIO.2

Import these packages:

This is the process to read a file:

To read all lines of a file at once:

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

There is no question that this is the easiest approach to understand, and if the file is fairly short (say, tens of thousands of lines), it’ll also be acceptable in terms of efficiency. But if the file is long, it’s a very inefficient way to do it, for two reasons:

If you care about speed, you are much better off reading a block of data and then processing it byte by byte rather than line by line. Every time you come to the end of a number, you add it to the List you’re building.

It will come out something like this:

The code above assumes that this is ASCII (though it could be easily tweaked for other encodings), and that anything that isn’t a digit (in particular, a space or a newline) represents a boundary between digits. It also assumes that the file ends with a non-digit (in practice, that the last line ends with a newline), though, again, it could be tweaked to deal with the case where it doesn’t.

Java – Read from File

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.

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:

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.

To work with FileChannel, keep in mind the following sequence:

3. DataInputStream

4. Read File Using Scanner

Another way to read a file with Java is through Scanner.

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:

For this example, we will create a new file with following data:

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:

Let’s see how to read this file using UTF-8 encoding

7. Read File using BufferReader and StringBuilder

BufferReader with StringBuilder is an efficient way to read a small file in Java

Above Example used the try-with-resources feature to auto-close stream.

Output

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:

8.1 Using Buffer Reader

We can also combine the Files class with the BufferReader. This can be helpful if you reading large files:

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:

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.

10.1 Apache FileUtils

Output

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.

10 Examples to read a text file in Java [UPDATED]

You can also use both BufferedReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.

The JDK 7 also introduces a couple of nice utility e.g. Files class and try-with-resource construct which made reading a text file, even more, easier.

In this article, I am going to share a couple of examples of reading a text file in Java with their pros, cons, and important points about each approach. This will give you enough detail to choose the right tool for the job depending on the size of file, the content of the file, and how you want to read.

1. Reading a text file using FileReader

Here is an example of reading a text file using FileReader in Java:

You can see that instead of reading one character at a time, I am reading characters into an array. This is more efficient because read() will access the file several times but read(char[]) will access the file just one time to read the same amount of data.

2. Reading a text file in Java using BufferedReader

The default size of the internal buffer is 8KB which is good enough for most purpose, but you can also increase or decrease buffer size while creating BufferedReader object. The reading code is similar to the previous example.

In this example as well, I am reading the content of the file into an array. Instead of reading one character at a time, this is more efficient. The only difference between the previous examples and this one is that the read() method of BufferedReader is faster than the read() method of FileReader because read can happen from memory itself.

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

3. Reading a text file in Java using Scanner

It does not just provide reading but the parsing of data as well. You can not only read text data but you can also read the text as a number or float using nextInt() and nextFloat() methods.

You can use the hasNext() method to determine if there is any more token left to read in the file and loop until it returns false. Though you should remember that next() or nextLine() may block until data is available even if hasNext() return true. This code is reading the content of «file.txt» line by line. See this tutorial to learn more about the Scanner class and file reading in Java.

4. Reading a text file using Stream in Java 8

The JDK 8 release has brought some cool new features e.g. lambda expression and streams which make file reading even smoother in Java. Since streams are lazy, you can use them to read-only lines you want from the file e.g. you can read all non-empty lines by filtering empty lines. The use of method reference also makes the file reading code much more simple and concise, so much so that you can read a file in just one line as shown below:

Now, if you want to do some pre-processing, here is code to trim each line, filter empty lines to only read non-empty ones, and remember, this is lazy because Files.lines() method return a stream of String and Streams are lazy in JDK 8 (see Java 8 in Action).

We’ll use this code to read a file that contains a line that is full of whitespace and an empty line, the same one which we have used in the previous example, but this time, the output will not contain 5 line but just three lines because empty lines are already filtered, as shown below:

You can see only three out of five lines appeared because the other two got filtered. This is just the tip of the iceberg on what you can do with Java SE 8, See Java SE 8 for Really Impatient to learn more about Java 8 features.

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

5. How to read a text file as String in Java

Sometimes you read the full content of a text file as String in Java. This is mostly the case with small text files as for large files you will face java.lang.OutOfMemoryError: java heap space error. Prior to Java 7, this requires a lot of boiler code because you need to use a BufferedReader to read a text file line by line and then add all those lines into a StringBuilder and finally return the String generated from that.

Now you don’t need to do all that, you can use the Files.readAllBytes() method to read all bytes of the file in one shot. Once done that you can convert that byte array into String. as shown in the following example:

This was a rather small file so it was pretty easy. Though, while using readAllBytes() you should remember character encoding. If your file is not in platform’s default character encoding then you must specify the character doing explicitly both while reading and converting to String. Use the overloaded version of readAllBytes() which accepts character encoding. You can also see how I read XML as String in Java here.

6. Reading the whole file in a List

Similar to the last example, sometimes you need all lines of the text file into an ArrayList or Vector or simply on a List. Prior to Java 7, this task also involves boilerplate e.g. reading files line by line, adding them into a list, and finally returning the list to the caller, but after Java 7, it’s very simple now. You just need to use the F iles.readAllLines() method, which returns all lines of the text file into a List, as shown below:

Similar to the last example, you should specify character encoding if it’s different from than platform’s default encoding. You can use see I have specified UTF-8 here. Again, use this trick only if you know that file is small and you have enough memory to hold a List containing all lines of the text file, otherwise your Java program will crash with OutOfMemoryError.

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

7. How to read a text file in Java into an array

This results in simple and elegant code, but you can also read data into a character array as shown in the first example. Use the read(char[] data) method while reading data into a character array.

Here is an example of reading a text file into String array in Java:

This method leverage our existing method which reads the file into a List and the code here is only to convert a list to an array in Java.

8. How to read a file line by line in Java

This is one of the interesting examples of reading a text file in Java. You often need file data as line by line. Fortunately, both BufferedReader and Scanner provide convenient utility method to read line by line. If you are using BufferedReader then you can use readLine() and if you are using Scanner then you can use nextLine() to read file contents line by line. In our example, I have used BufferedReader as shown below:

How to read from file java. Смотреть фото How to read from file java. Смотреть картинку How to read from file java. Картинка про How to read from file java. Фото How to read from file java

Java Program to read a text file in Java

I have not printed the output here because we have already gone through that and discuss in respective examples, but you need Java 8 to compile and run this program. If you are running on Java 7, then just remove the example 4 and 5 which uses Java 8 syntax and features and the program should run fine.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *