Java ByteArrayOutputStream & ByteArrayInputStream: Streams in memory








Java ByteArrayOutputStream & ByteArrayInputStream are the stream in memory. For example, you can read a text file into memory using ByteArrayInputStream. See the example below:
    public static InputStream readFile(File f) throws Throwable {
        Reader r = new BufferedReader(new FileReader(f));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Writer w = new OutputStreamWriter(baos);
        char[] buffer = new char[2048];
        try {
            int n;
            while((n = r.read(buffer, 0, 2048))!=-1){
                w.write(buffer, 0, n);
            }
        } finally {
            r.close();
        }
        return new ByteArrayInputStream(baos.toByteArray());
    }

See also




No comments:

Post a Comment