[英]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.