簡體   English   中英

在 Android 中尋找 InputStream - Java

[英]Seeking on an InputStream in Android - Java

我有一個文件傳輸應用程序,它通過套接字連接將大文件(大小為幾 GB)從 Android 發送到 Windows。 我正在使用內容解析器將輸入 stream 實例輸入到存儲在手機中的文件,但我希望能夠在輸入 stream 上來回搜索,以使文件傳輸通過數據報通道更有效。 有沒有辦法做到這一點?

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);
}

這是一種對我有用的值得嘗試的方法。 這個想法是通過獲取 AssetFileDescriptor 將 InputStream 轉換為 FileInputStream,然后獲取一個 FileChannel 實例,讓您來回查找。

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();
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM