Skip to content Skip to sidebar Skip to footer

Read A Segment Of A File In Java / Android

I'm sure this might be a simple question, but unfortunately this is my first time using Java and working the Android SDK. I am uploading files on Android using the Apache HTTP libr

Solution 1:

You can either use the skip(long) method to skip the number of bytes in the InputStream or you can create a RandomAccessFile on the File object and call its seek(long) method to set the pointer to that position so you can start reading from there.

The quick test below reads in a 4mb+ file (between 3m and 4mb) and writes the read data to an ".out" file.

import java.io.*;
import java.util.*;

publicclassTest {

    publicstaticvoidmain(String[] args)throws Throwable {
       longthreeMb=1024 * 1024 * 3;
       Fileassembled=newFile(args[0]); // your downloaded and assembled fileRandomAccessFileraf=newRandomAccessFile(assembled, "r"); // read
       raf.seek(threeMb); // set the file pointer to 3mbintbytesRead=0;
       inttotalRead=0;
       intbytesToRead=1024 * 1024; // 1MB (between 3M and 4MFilef=newFile(args[0] + ".out");
       FileOutputStreamout=newFileOutputStream(f);

       byte[] buffer = newbyte[1024 * 128]; // 128k buffer while(totalRead < bytesToRead) { // go on reading while total bytes read is// less than 1mb
         bytesRead = raf.read(buffer);
         totalRead += bytesRead;
         out.write(buffer, 0, bytesRead);
         System.out.println((totalRead / 1024));
       }
    }
}

Solution 2:

Use skip() method of FileInputStream stream to seek to the fragment you need.

Solution 3:

I was able to figure it out... just had to discover that there's a ByteArrayInputStream that would allow me to convert my byte[] buffer to an InputStream. From here on, I can now track which chunks failed and handle it. Thanks Konstantin for Here's my implementation:

finalintchunkSize=512 * 1024; // 512 kBfinallongpieces= file.length() / chunkSize;
    intchunkId=0;

    HttpPostrequest=newHttpPost(endpoint);

    BufferedInputStreamstream=newBufferedInputStream(newFileInputStream(file));

    for (chunkId = 0; chunkId < pieces; chunkId++) {
        byte[] buffer = newbyte[chunkSize];

        stream.skip(chunkId * chunkSize);
        stream.read(buffer);

        MultipartEntityentity=newMultipartEntity();
        entity.addPart("chunk_id", newStringBody(String.valueOf(chunkId)));
        request.setEntity(entity);
        ByteArrayInputStreamarrayStream=newByteArrayInputStream(buffer);

        entity.addPart("file_data", newInputStreamBody(arrayStream, filename));

        HttpClientclient= app.getHttpClient();
        client.execute(request);
    }

Post a Comment for "Read A Segment Of A File In Java / Android"