![](/img/trans.png)
[英]? How can I list all files in directory or drive without using stream and sort it by creation date using just nio api in java
[英]How we can stream a CSV file using Java NIO Api?
我正在尝试使用 java NIO stream 一个大的 CSV 文件,我能够从 CSV 文件中读取数据。 请提出任何示例,我们如何 stream 一个 CSV 文件。 我们需要在下面的代码中附加/更改哪些代码。
请看下面的代码。
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();
}
}
任何帮助将不胜感激。 提前致谢 !!
在像CSV这样逐行格式的文件上使用RandomAccessFile
没有多大意义。
调用 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.