简体   繁体   中英

How we can stream a CSV file using Java NIO Api?

I am trying to stream a Big CSV file using java NIO, I am able to read the Data from CSV file. Please suggest any example how we can stream a CSV file. What code we need to append/changes in this below code.

Please see below code.

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
public class ReadFileWithFixedSizeBuffer 
{
    public static void main(String[] args) throws IOException 
    {
        RandomAccessFile aFile = new RandomAccessFile("airQuality.csv", "r");
 
        FileChannel inChannel = aFile.getChannel();
 
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while(inChannel.read(buffer) > 0)
        {
            buffer.flip();
            for (int i = 0; i < buffer.limit(); i++)
            {
                System.out.print((char) buffer.get());
            }
            buffer.clear(); // do something with the data and clear/compact it.
        }
 
        inChannel.close();
        aFile.close();
    }
}

Any Help would be appreciate. Thanks in advance !!

There isn't much point using RandomAccessFile on files which are line by line format like CSV .

Calling NIO Files.lines() will simplify your logic, and try with resources cleans up your file handling neatly:

Path file = Path.of("airQuality.csv");

try(Stream<String> lines = Files.lines(file))
{
    lines.forEach(line -> {
        // Do something with each line here instead of:
        System.out.println(line);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM