简体   繁体   English

我们如何使用 stream CSV 文件使用 Java NIO Api?

[英]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.我正在尝试使用 java NIO stream 一个大的 CSV 文件,我能够从 CSV 文件中读取数据。 Please suggest any example how we can stream a CSV file.请提出任何示例,我们如何 stream 一个 CSV 文件。 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 .在像CSV这样逐行格式的文件上使用RandomAccessFile没有多大意义。

Calling NIO Files.lines() will simplify your logic, and try with resources cleans up your file handling neatly:调用 NIO Files.lines()将简化您的逻辑,并尝试使用资源整洁地清理您的文件处理:

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);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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