MainClass.java Source code

Java tutorial

Introduction

Here is the source code for MainClass.java

Source

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainClass {

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

        if (args.length != 3) {
            System.out.println("Usage: java TeeCopier infile outfile1 outfile2");
            return;
        }

        FileInputStream fin = new FileInputStream(args[0]);
        FileOutputStream fout1 = new FileOutputStream(args[1]);
        FileOutputStream fout2 = new FileOutputStream(args[2]);
        MyOutputStream tout = new MyOutputStream(fout1, fout2);
        copy(fin, tout);
        fin.close();
        tout.close();
    }

    public static void copy(InputStream in, OutputStream out) throws IOException {

        byte[] buffer = new byte[1024];
        while (true) {
            int bytesRead = in.read(buffer);
            if (bytesRead == -1)
                break;
            out.write(buffer, 0, bytesRead);
        }
    }
}

class MyOutputStream extends FilterOutputStream {

    private OutputStream out1;

    private OutputStream out2;

    public MyOutputStream(OutputStream stream1, OutputStream stream2) {
        super(stream1);
        out1 = stream1;
        out2 = stream2;
    }

    public void write(int b) throws IOException {
        out1.write(b);
        out2.write(b);
    }

    public void write(byte[] data, int offset, int length) throws IOException {
        out1.write(data, offset, length);
        out2.write(data, offset, length);
    }

    public void flush() throws IOException {
        out1.flush();
        out2.flush();
    }

    public void close() throws IOException {
        out1.close();
        out2.close();
    }
}