文件的切割与合并

文件的切割:创建一个输入流来读取文件,创建多个输出流来写碎片文件,写完一个输出流就关一个。

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

public class IoDemo {
    public static void main(String[] args) throws IOException {
        File f = new File("e:/lishuai.txt");
        cutmethord(f);
    }

    private static void cutmethord(File f) throws IOException {
        // TODO Auto-generated method stub
        FileInputStream fi = new FileInputStream(f);
        int len = 0;
        // 定义碎片文件名
        int count = 1;
        byte[] b = new byte[1024];
        while ((len = fi.read(b)) != -1) {
            FileOutputStream fo = new FileOutputStream("e:/"+count+".txt");
            fo.write(b, 0, len);
            fo.close();
            count++;
        }
        fi.close();
    }
}

文件的关闭:文件的合并与文件的切割思想相反,先创建一个输出流对象,之后遍历碎片文件,边读边写。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class IoDemo {
    public static void main(String[] args) throws IOException {
        methord();
    }

    private static void methord() throws IOException {
        // TODO Auto-generated method stub
        FileOutputStream fo = new FileOutputStream("e:/lishuai.txt");
        for (int i = 1; i <= 3; i++) {
            FileInputStream fi = new FileInputStream("e:/" + i + ".txt");
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = fi.read(b)) != -1) {
                fo.write(b, 0, len);
            }
            fi.close();
        }
        fo.close();
    }
}

你可能感兴趣的:(文件的切割与合并)