Use ByteArrayOutputStream : ByteArrayOutputStream « File Input Output « Java






Use ByteArrayOutputStream

    

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayIOApp {
  public static void main(String args[]) throws IOException {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    String s = "This is a test.";
    for (int i = 0; i < s.length(); ++i)
      outStream.write(s.charAt(i));
    System.out.println("outstream: " + outStream);
    System.out.println("size: " + outStream.size());
    ByteArrayInputStream inStream;
    inStream = new ByteArrayInputStream(outStream.toByteArray());
    int inBytes = inStream.available();
    System.out.println("inStream has " + inBytes + " available bytes");
    byte inBuf[] = new byte[inBytes];
    int bytesRead = inStream.read(inBuf, 0, inBytes);
    System.out.println(bytesRead + " bytes were read");
    System.out.println("They are: " + new String(inBuf));
  }
}

   
    
    
  








Related examples in the same category

1.An unsynchronized version of java.io.ByteArrayOutputStream
2.A speedy implementation of ByteArrayOutputStream.
3.Provides true Closable semantics ordinarily missing in a java.io.ByteArrayOutputStream
4.Read byte and string with ByteArrayOutputStream