Read a segment of a file in Java / Android

后端 未结 3 2016
难免孤独
难免孤独 2021-01-13 04:59

I\'m sure this might be a simple question, but unfortunately this is my first time using Java and working the Android SDK.

I am uploading files on Android using the

3条回答
  •  星月不相逢
    2021-01-13 05:23

    You can either use the skip(long) method to skip the number of bytes in the InputStream or you can create a RandomAccessFile on the File object and call its seek(long) method to set the pointer to that position so you can start reading from there.

    The quick test below reads in a 4mb+ file (between 3m and 4mb) and writes the read data to an ".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));
           }
        }
    }
    

提交回复
热议问题