我有一个管道,我需要从中读取数据。 但是,正如我在阅读之前所理解的,我必须创建一些大小的缓冲区。 问题是如何定义缓冲区的大小来读取管道中的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.
更多推荐
发布评论