Showing posts with label Input Stream. Show all posts
Showing posts with label Input Stream. Show all posts

Tuesday, February 23, 2016

Java Clone/Copy InputStream


package com.pritom.kumar;


import java.io.*;

/**
 * Created by pritom on 23/02/2016.
 */
public class CloneInputStream {
    public static void main(String[] args) throws Exception {
        File file = new File("input.csv");
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        System.out.println("Length1=" + inputStreamToString(inputStream).length());
        InputStream inputStreamCloned = clone(inputStream);
        System.out.println("Length2=" + inputStreamToString(inputStreamCloned).length());
        inputStreamCloned = clone(inputStream);
        System.out.println("Length3=" + inputStreamToString(inputStreamCloned).length());

        inputStream = new BufferedInputStream(new ByteArrayInputStream("Pritom Kumar".getBytes()));
        System.out.println("\nLength1=" + inputStreamToString(inputStream).length());
        inputStreamCloned = clone(inputStream);
        System.out.println("Length2=" + inputStreamToString(inputStreamCloned).length());
        inputStreamCloned = clone(inputStream);
        System.out.println("Length3=" + inputStreamToString(inputStreamCloned).length());
    }

    public static InputStream clone(final InputStream inputStream) {
        try {
            inputStream.mark(0);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int readLength = 0;
            while ((readLength = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, readLength);
            }
            inputStream.reset();
            outputStream.flush();
            return new ByteArrayInputStream(outputStream.toByteArray());
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String inputStreamToString(final InputStream inputStream) {
        try {
            Writer writer5 = new StringWriter();
            Reader reader = new BufferedReader(new InputStreamReader(clone(inputStream), "UTF-8"));
            int readLength = 0;
            char[] buffer = new char[1024];
            while ((readLength = reader.read(buffer)) != -1) {
                writer5.write(buffer, 0, readLength);
            }
            return writer5.toString();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}

Output

Length1=5357
Length2=5357
Length3=5357

Length1=12
Length2=12
Length3=12