Java:如何定义缓冲区的大小以从FileChannel读取所有数据(Java: how to define the size of buffer to read all data from File

编程入门 行业动态 更新时间:2024-10-27 23:22:05
Java:如何定义缓冲区的大小以从FileChannel读取所有数据(Java: how to define the size of buffer to read all data from FileChannel)

我有一个管道,我需要从中读取数据。 但是,正如我在阅读之前所理解的,我必须创建一些大小的缓冲区。 问题是如何定义缓冲区的大小来读取管道中的all数据?

这是我的代码:

RandomAccessFile aFile = new RandomAccessFile(PIPE_FILE, "r"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(4);//temp 4 while(true){ System.out.println("Size:"+inChannel.size());//returns 0 int bytesRead = inChannel.read(buf); byte [] bytes=buf.array(); ... buf.clear(); }

I have a pipe and I need to read data from it. However, as I understand before reading I must create buffer of some size. The question is how to define the size of buffer to read all data from pipe?

This is my code:

RandomAccessFile aFile = new RandomAccessFile(PIPE_FILE, "r"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(4);//temp 4 while(true){ System.out.println("Size:"+inChannel.size());//returns 0 int bytesRead = inChannel.read(buf); byte [] bytes=buf.array(); ... buf.clear(); }

最满意答案

与文件不同,管道没有固定的大小:我们知道,管道另一端的编写器可以将通过算法创建的数据推送给您,因此管道流可以是无限的。

您需要创建一个大小的缓冲区,通常是几百到几千字节,在循环中从管道中读取,并且要么随意处理数据流,要么将其保存在循环中的动态分配缓冲区中。

Unlike a file, a pipe does not have a fixed size: for all we know, the writer on the other end of the pipe can be pushing data created algorithmically to you, so the pipe stream could be infinite.

You need to create a buffer of some size, usually in a hundreds to thousand bytes, read from the pipe in a loop, and either process the data stream as you go, or save it in a dynamically allocated buffer in a loop.

更多推荐

本文发布于:2023-08-03 14:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390556.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓冲区   定义   大小   数据   FileChannel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!