简体   繁体   中英

Seeking on an InputStream in Android - Java

I have a file transfer app that sends large files (few GBs in size) from Android to Windows over a socket connection. I am using content resolver to get input stream instance to the file stored in the phone, but I want to be able to seek back and forth on the input stream to make file transfer more efficient over Datagram channel. Is there a way to do that?

int ack, len;

Context context = getApplicationContext();
ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(fileUri);

while ((len = is.read(bufr, 0, BUFFER_SIZE)) > 0) {
        ack = sendDatagramPacket(bufr, 0, len);
}

Here's one approach worth trying that worked for me. The idea is to cast InputStream to FileInputStream by getting AssetFileDescriptor, and then getting an instance of FileChannel that lets you seek back and forth.

long position = 0, bytesRead = 0, currentRead = 0;

Context context = getApplicationContext();
ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(fileUri);
AssetFileDescriptor assetFileDescriptor = null;
FileInputStream fis = null;
FileChannel fc = null;

        try {
            assetFileDescriptor = getContentResolver().openAssetFileDescriptor(fileUri[0], "r");
            is = cr.openInputStream(fileUri[0]);
            Utility.sendFileInfo(is, out, fileName);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        fis = new FileInputStream(assetFileDescriptor.getFileDescriptor());;
        fc = fis.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(Utility.BUFFER_SIZE);

        while(position < filesize){
            try {
                fc.position(position);
                currentRead = fc.read(buffer);

                //Use the populated buffer to send data out
                SendDatagramPacket(buffer, 0, currentRead)
                bytesRead += currentRead;
                position = bytesRead;
                buffer = ByteBuffer.allocate(Utility.BUFFER_SIZE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM