?java——将两个文件合并为一个文件

2019年2月23日17:29:25 发表评论 1,705 views
import java.io.*;
public class squencedemo {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        //声明两个文件读入流
        FileInputStream in1 = null, in2 = null;
        //声明一个序列流
        SequenceInputStream s = null;
        FileOutputStream out = null;
        try {
            //构造两个被读入的文件
            File inputFile1 = new File("c:\\11.txt");
            File inputFile2 = new File("c:\\22.txt");
            //构造一个输出文件
            File outputFile = new File("c:\\12.txt");

            in1 = new FileInputStream(inputFile1);
            in2 = new FileInputStream(inputFile2);
            //将两个流合为一个输入流
            s = new SequenceInputStream(in1, in2);
            out = new FileOutputStream(outputFile);

            int c;
            while ((c = s.read()) != -1)
                out.write(c);//为什么不是重复写入???
            in1.close();
            in2.close();
            s.close();
            out.close();
            System.out.println("ok...");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in1 != null)
                try {
                    in1.close();
                } catch (IOException e) {

                }
            if (in2 != null)
                try {
                    in2.close();
                } catch (IOException e) {

                }
            if (s != null)
                try {
                    s.close();
                } catch (IOException e) {
                }
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                }

            }
        }


    }

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: