Read/Write to linux Pipe using Java

amit.bhayani picture amit.bhayani · Oct 27, 2009 · Viewed 15.3k times · Source

My query is on what is the best way to read / write to a linux Pipe in Java? I already am using the java.io.RandomAccessFile like

   RandomAccessFile file = new RandomAccessFile("/dev/zap/16", "rw");

and then passing it to worker thread which reads it after every 2ms as

  byte[] buffer = new byte[16];
  file.read(buffer);

It does read it from Pipe, but I suspect that some bytes are overwritten. Do you know how linux (ubuntu) handles the buffer for pipe's?

Answer

sfussenegger picture sfussenegger · Oct 27, 2009

I haven't ever tried this myself but what your doing feels just wrong. Linux pipes are First in - First out (FIFO) by definition. Hence you should only be able to read bytes in the same order as you've written them - not randomly. I'd suggest to use a normal File instead and it should work fine.