我确信这可能是一个简单的问题,但不幸的是这是我第一次使用 Java 和 Android SDK。
我使用 Apache HTTP 库,特别是使用 MultipartEntity 在 Android 上上传文件。
我正在上传到一个服务,该服务允许我向他们发送文件块,一旦完成,他们将重新组装这些块。我想利用这个功能。
这是场景。
文件 FOO.BAR 为 20 MB。我将其分成任意大小的块,比方说 1 MB,这意味着 20 个块。块 #3 和 #14 失败(可能是蜂窝/WiFi 连接不良)。我现在可以重新上传这两个块,一切都会好起来的。
我想知道的是如何只读取文件的一部分(例如 3MB 到 4MB 之间的数据)?
文件片段应该是一个InputStream 或File 对象。
谢谢,
诚
您可以使用跳过(长)方法来跳过 InputStream 中的字节数,或者您可以在 File 对象上创建 RandomAccessFile 并调用其寻找(长)方法将指针设置到该位置,以便您可以从那里开始阅读。
下面的快速测试读取 4mb+ 文件(3m 到 4mb 之间)并将读取的数据写入".out"
file.
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
long threeMb = 1024 * 1024 * 3;
File assembled = new File(args[0]); // your downloaded and assembled file
RandomAccessFile raf = new RandomAccessFile(assembled, "r"); // read
raf.seek(threeMb); // set the file pointer to 3mb
int bytesRead = 0;
int totalRead = 0;
int bytesToRead = 1024 * 1024; // 1MB (between 3M and 4M
File f = new File(args[0] + ".out");
FileOutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[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));
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)