在Java / Android中读取文件的一部分

我确信这可能是一个简单的问题,但不幸的是,这是我第一次使用Java并使用Android SDK。

我使用Apache HTTP库在Android上上传文件,特别是使用MultipartEntity。

我正在上传到一个允许我发送文件块的服务,一旦完成,他们就会重新组装这些块。 我想利用这个function。

这是场景。

文件FOO.BAR是20 MB。 我将它分成一些任意的块大小,比方说1 MB,这意味着20块。 块#3和#14失败(可能是蜂窝/ WiFi连接不好)。 我现在可以重新上传这两个块,一切都会好的。

我想知道的是如何只读取文件的一部分(如3MB和4MB之间的数据)?

文件块应该是InputStream或File对象。

谢谢,Makoto

您可以使用skip(long)方法跳过InputStream中的字节数,也可以在File对象上创建RandomAccessFile并调用其seek(long)方法将指针设置为该位置,这样您就可以开始读取那里。

下面的快速测试读取4mb +文件(3m到4mb之间)并将读取的数据写入".out"文件。

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

我能够弄明白……只需要发现有一个ByteArrayInputStream可以让我将byte []缓冲区转换为InputStream。 从现在开始,我现在可以跟踪哪些块失败并处理它。 谢谢康斯坦丁这里是我的实施:

  final int chunkSize = 512 * 1024; // 512 kB final long pieces = file.length() / chunkSize; int chunkId = 0; HttpPost request = new HttpPost(endpoint); BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file)); for (chunkId = 0; chunkId < pieces; chunkId++) { byte[] buffer = new byte[chunkSize]; stream.skip(chunkId * chunkSize); stream.read(buffer); MultipartEntity entity = new MultipartEntity(); entity.addPart("chunk_id", new StringBody(String.valueOf(chunkId))); request.setEntity(entity); ByteArrayInputStream arrayStream = new ByteArrayInputStream(buffer); entity.addPart("file_data", new InputStreamBody(arrayStream, filename)); HttpClient client = app.getHttpClient(); client.execute(request); } 

使用FileInputStream流的skip()方法来寻找您需要的片段。