Java - An Efficient Stream Copier

public class StreamCopier {

    public static void main(String[] args) {
        try {
            copy(System.in, System.out);
        } catch (IOException e) {
            System.out.println(e);
        }

    }

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

         /*複製過程中,不允許其他執行緒讀取輸入串流或寫入輸出串流*/
        synchronized (in) {
            synchronized (out) {
                byte[] buffer = new byte[256];
                while (true) {
                    int bytesRead = in.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    }
                    out.write(buffer, 0, bytesRead);
                }
            }
        }
    }
}

你可能感兴趣的:(java)