Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading file chunk by chunk

I want to read a file piece by piece. The file is split up into several pieces which are stored on different types of media. What I currently do is call each seperate piece of the file and then merge it back to the original file.

The issue is that I need to wait until all the chunks arrive before I can play/open the file. Is it possible to read the chunks as they are arriving as opposed to waiting for them to all arrive.

I am working on media file (movie file).

like image 262
david Avatar asked Jun 19 '12 22:06

david


2 Answers

See InputSteram.read(byte[]) for reading bytes at a time.

Example code:

try {
    File file = new File("myFile");
    FileInputStream is = new FileInputStream(file);
    byte[] chunk = new byte[1024];
    int chunkLen = 0;
    while ((chunkLen = is.read(chunk)) != -1) {
        // your code..
    }
} catch (FileNotFoundException fnfE) {
    // file not found, handle case
} catch (IOException ioE) {
    // problem reading, handle case
}
like image 197
cklab Avatar answered Oct 17 '22 21:10

cklab


what you want is source data line. This is perfect for when your data is too large to hold it in memory at once, so you can start playing it before you receive the entire file. Or if the file never ends.

look at the tutorial for source data line here

http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read

I would use this FileInputSteam

like image 30
Frank Visaggio Avatar answered Oct 17 '22 22:10

Frank Visaggio