java—输入输出流

编写将两个文件(文件1、文件2)中的内容合并成一个新文件(文件3)。合并方法是:从文件1读取一个字节放入文件3,在从文件2读取一个字节放入文件3,如此轮流直至某一个文件读完,再将较长文件中的剩余部分读取放入至文件3。可以使用图形界面或命令行参数输入三个文件名。

这是纯字节写入的,如果要字符的还要改

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class FileWriter {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("请输入文件1的路径:");
        // Reading data using readLine
        String path1 = reader.readLine();

        System.out.println("请输入文件2的路径:");
        // Reading data using readLine
        String path2 = reader.readLine();

        System.out.println("请输入文件3的路径:");
        // Reading data using readLine
        String path3 = reader.readLine();

        FileInputStream bStream = new FileInputStream(path1);
        byte[] b1 = bStream.readAllBytes();
        bStream.close();
        FileInputStream bStream2 = new FileInputStream(path2);
        byte[] b2 = bStream2.readAllBytes();
        bStream2.close();

        ArrayList<Byte> b3 = new ArrayList<Byte>();
        int i = 0;
        while (i < Math.max(b1.length, b2.length)) {
            if (i < b1.length) {
                b3.add(b1[i]);
            }
            if (i < b2.length) {
                b3.add(b2[i]);
            }
            i++;
        }
        byte[] brr = new byte[b3.size()];
        for (Byte b : b3) {
            brr[b3.indexOf(b)] = b;
        }
        File file = new File(path3);
        try (FileOutputStream fout = new FileOutputStream(file)) {
            fout.write(brr);
        }
    }
}