课后作业----大文件分割

编写一个文件分割工具,能把一个大文件分割成多个小的文件。并且能再次把它们合并起来得到完整的文件。

 

思路:大文件分割其实就是把文件内容平均分到多个小文件,可以定义一个大小作为平均大小,然后才进行文件操作。至于合并,则把这几个文件内容依次读入到一个新的文件。

代码:

package com.testHomework;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileBreakUp {
    private static int name = 1;
    public static void main(String[] args) {
        File file1 = new File("D:/java文件/Harry Potter and the Sorcerer's Stone.txt");
        File file2 = new File("D:/java文件");
        //BreakUp(file1,file2,1024*100);
        Mix(new File("D:/java文件/mix.txt"),new File("D:/java文件"));
    }
    
    // 文件分割
    public static void BreakUp(File file1,File file2,int size) {
        File file = file1;
        InputStream is = null;
        OutputStream os = null;

        try {
            is = new FileInputStream(file);
            byte[] flush = new byte[size];
            int len = -1;
            try {
                while((len=is.read(flush))!=-1) {        
                    os = new FileOutputStream(file2.getAbsolutePath()+File.separatorChar+"break"+name+".txt");
                    os.write(flush, 0, len);
                    os.close();
                    name++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    // 文件合并
    public static void Mix(File file1,File file2) {
        File file = file2;
        InputStream is = null;
        OutputStream os = null;
        try {
            os = new FileOutputStream(file1);
            byte[] flush = new byte[1024*100];
            int len = -1,num=1;
            try {
                while(num<=5) {
                    is = new FileInputStream(file2.getAbsolutePath()+File.separatorChar+"break"+num+".txt");
                    while((len=is.read(flush))!=-1) {                                        
                        os.write(flush, 0, len);
                    }
                    num++;
                }        
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

运行结果:拆分结果:

 

 合并结果:

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/yangxiao-/p/11832323.html
今日推荐