6

I'm using a propriatery Java library that saves its data directly into a java.io.File, but I need be able to read the data so it's directly streamed. Data is binary, some media file.

The java.io.File is passed as an argument to this library, but I don't know of a way to get a stream out of it. Is there some simple way to do this, except opening the file also for reading and trying to sync read/write operations!?

Prefferably I would like to skip the writing to the file system part since I'm using this from an applet and in this case need extra permissions.

Gray
  • 115,027
  • 24
  • 293
  • 354
user1015922
  • 173
  • 1
  • 4
  • 1
    If you could pass it an OutputStream instead, that would be easier. Is that an option? – laher Oct 27 '11 at 06:22

2 Answers2

4

If one part of your program is writing to a file, then you should be able to read from that file using a normal new FileInputStream(someFile) stream in another thread although this depends on OS support for such an action. You don't need to synchronize anything. Now, you are at the mercy of the output stream and how often the writing portion of your program calls flush() so there may be a delay.

Here's a little test program that I wrote demonstrating that it works fine. The reading section just is in a loop looks something like:

FileInputStream input = new FileInputStream(file);
while (!Thread.currentThread().isInterrupted()) {
    byte[] bytes = new byte[1024];
    int readN = input.read(bytes);
    if (readN > 0) {
        byte[] sub = ArrayUtils.subarray(bytes, 0, readN);
        System.out.print("Read: " + Arrays.toString(sub) + "\n");
    }
    Thread.sleep(100);
}
Gray
  • 115,027
  • 24
  • 293
  • 354
  • 2
    Depends on the OS. Some won't let you write to a file that's being read...others have all kinds of trouble or require special "sharing" modes in order to do so. Windows in particular seems to hate it. – cHao Oct 28 '11 at 18:26
  • So in Windows, in the same application you can't read your own files without some "sharing" modes? Did not know that. – Gray Oct 28 '11 at 19:55
  • +1 for providing an example. Also, best to never use Windows. ;-) – Jeremy Brooks Sep 17 '13 at 17:26
  • Is it expensive to poll the FileInputStream every 100ms? – masterwok Feb 14 '18 at 09:29
  • Expense is relative @masterwok but that does seem like a lot of IO. Maybe instead you can look at the file's length and only open it if it has changed? i.e. `new File("some/path").length()`. – Gray Feb 14 '18 at 17:02
0

assuming file writing behaviour is intrinsic to the library, you should check its documentation to see if you can avoid writing to the file system. Generally speaking, if you want to read a file that is being written to (i.e. *nix tail-like behaviour), you can use java.io.RandomAccessFile

aishwarya
  • 1,970
  • 1
  • 14
  • 22