如何使用字节流将Java中的文件拆分为多个相同大小的部分

时间:2018-11-28 13:54:53

标签: java file split

以下是我尝试过的代码。我能够读取100KB的文件 song.mp3(总大小为2.4MB),但无法读取后续块(100KB) 在循环。该循环仅创建文件song_0.mp3,并且为空。 我需要将文件创建为song_0.mp3,song_1.mp3,...

public class fileIOwrite2multiplefiles {
        public static void main(String[] args) throws IOException{
        // TODO code application logic here

        File file = new File("song.mp3");

        FileInputStream fIn = new FileInputStream("song.mp3");
        FileOutputStream fOut = new FileOutputStream("song_0.mp3");
        int chunk_size = 1024*100;
        byte[] buff = new byte[chunk_size]; // 100KB file 

        while(fIn.read()!=-1){

          fIn.read(buff);
          String file_name =file.getName();
          int i=1;
          int total_read=0;
          total_read +=chunk_size;
          long read_next_chunk= total_read;
          String file_name_new = file_name+"_"+ i +".mp3";
          File file_new = new File(file_name);
          i++;
          fOut = new FileOutputStream(file_name_new);
          fOut.write(buff);
          buff = null;
          fIn.skip(total_read);// skip the total read part


       }//end of while loop      

        fIn.close();
        fOut.close();          
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将主方法重写为:

public static void main(String[] args) throws IOException {

    File file = new File("song.mp3");

    FileInputStream fIn = new FileInputStream("song.mp3");
    FileOutputStream fOut = new FileOutputStream("song_0.mp3");
    int chunk_size = 1024 * 100;
    byte[] buff = new byte[chunk_size]; // 100KB file
    int i = 0;
    String file_name = file.getName();
    String file_name_base = file_name.substring(0, file_name.lastIndexOf("."));
    while (fIn.read() != -1) {

        fIn.read(buff);
        int total_read = 0;
        total_read += chunk_size;
        long read_next_chunk = total_read;
        String file_name_new = file_name_base + "_" + i + ".mp3";
        File file_new = new File(file_name_base);
        i++;
        fOut = new FileOutputStream(file_name_new);
        fOut.write(buff);

        fIn.skip(total_read);// skip the total read part

    } // end of while loop

    fIn.close();
    fOut.close();

}
  1. 在while循环之外创建增量变量声明( int i = 0 )是必需的。
  2. 不要使变量 buff 为空,因为它将在下一次迭代中抛出Null指针。
  3. 需要提取文件的基本名称,以便使用所需名称创建文件部分。例如。 song_0.mp3,song_1.mp3,...