Java Read a text file line by line

摘要: This article covers 3 ways to read a text file line by line :

This article covers 3 ways to read a text file line by line :

  1. Java NIO libraries – FileChannel to read the files. It is a non-blocking mode of reading files
  2. BufferedReader – Which is a blocking operation i.e it blocks any other read/write request to the file until it has completed the task.
  3. Apache Commons IO – FileUtils, simpler way to read files line by line. It is also a blocking operation.

The input file for each example is same as the one shown below:

src/com/mkyong/data.txt

1. Java NIO libraries

The example presents the simplest way of reading a small file. Since this is a small file, we directly allocate required memory to ByteBuffer using FileChannel size.

NIOFileReadExample.java
package com.mkyong;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileReadExample {
    public static void main(String[] args) throws IOException {
        RandomAccessFile file = new RandomAccessFile("src/com/mkyong/data.txt", "r");
        FileChannel channel = file.getChannel();
        System.out.println("File size is: " + channel.size());
        ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
        channel.read(buffer);
        buffer.flip();//Restore buffer to position 0 to read it
        System.out.println("Reading content and printing ... ");
        for (int i = 0; i < channel.size(); i++) {
            System.out.print((char) buffer.get());
        channel.close();
        file.close();

On executing the code you get the below output:

File size is: 19
Reading content and printing ... 

2. BufferedReader

ReadTextFile.java
package com.mkyong;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadTextFile {
    public static void main(String[] args) throws IOException {
        try {
            File f = new File("src/com/mkyong/data.txt");
            BufferedReader b = new BufferedReader(new FileReader(f));
            String readLine = "";
            System.out.println("Reading file using Buffered Reader");
            while ((readLine = b.readLine()) != null) {
                System.out.println(readLine);
        } catch (IOException e) {
            e.printStackTrace();

The output on executing this code will be as shown below:

Reading file using Buffered Reader

3. Apache Commons IO

pom.xml
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
  </dependency>
FileIOUtilsExample
package com.mkyong;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class ReadTextFile {
    public static void main(String[] args) throws IOException {
        try {
            File f = new File("src/com/mkyong/data.txt");
            System.out.println("Reading files using Apache IO:");
            List<String> lines = FileUtils.readLines(f, "UTF-8");
            for (String line : lines) {
                System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();

The output on executing above code will be:

Reading files using Apache IO:

References

  1. More about BufferedReader
  2. More about FileReader
  3. BufferedReader examples
  4. Java 8 stream to read file line by line
  5. More about FileChannel functions
  6. Difference between ByteBuffer flip() and rewind() methods
  7. ByteBuffer javadocs
  8. FileChannel Javadocs
  9. Apache Commons IO user guide

上一篇: Java Cron job to run a jar file
下一篇: Create a fat Jar file Maven Shade Plugin
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号