【问题标题】:Seeking on an InputStream in Android - Java在 Android 中寻找 InputStream - Java
【发布时间】:2020-08-04 05:35:54
【问题描述】:

我有一个文件传输应用程序,它通过套接字连接将大文件(大小为几 GB)从 Android 发送到 Windows。我正在使用内容解析器将输入流实例获取到存储在手机中的文件,但我希望能够在输入流上来回搜索,以使文件传输通过数据报通道更有效。有没有办法做到这一点?

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

【问题讨论】:

  • Int len 可能不等于 BUFFER_SIZE。因此缓冲区可能没有被完全填满。试试看:ack = sendDatagramPacket(bufr, 0, len);
  • 谢谢,我写了这个sn-p的代码来简化实际的代码。我现在包含了您的编辑。

标签: java android socket.io inputstream


【解决方案1】:

这是一种对我有用的值得尝试的方法。这个想法是通过获取 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();
            }
        }

【讨论】:

    猜你喜欢
    • 2013-12-09
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多