Reputation:
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();
}
Upvotes: 2
Views: 453
Reputation: 352
I am not allowed to send comments yet, so I will answer based on my understanding:
I will focus on the fact this is a RandomAccessFile.
As suggested in another answer, regardless of the size of your buffer, you can read it in a loop up to the end:
while(inChannel.read(buf) >= 0)
{
}
Other than that, to answer your initial question precisely, even though your file/pipe will most likely keep growing, at a given time it has a size, so you can use that for your buffer, but if in-between file is modified then this could lead to incomplete read or even errors (for example if pipe would be cleared or something like that):
ByteBuffer buf = ByteBuffer.allocate(inChannel.size());
Upvotes: 0
Reputation: 726669
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.
Upvotes: 2