Java by API/java.io/ByteArrayOutputStream

Материал из Java эксперт
Перейти к: навигация, поиск

ByteArrayOutputStream: toByteArray()

 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Main {
  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 = 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));
  }
}





ByteArrayOutputStream: writeTo(OutputStream out)

  
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
  public static void main(String args[]) throws IOException {
    int howMany = 20;
    // To avoid resizing the buffer, calculate the size of the
    // byte array in advance.
    ByteArrayOutputStream bout = new ByteArrayOutputStream(howMany * 4);
    DataOutputStream dout = new DataOutputStream(bout);
    for (int i = 0; i <= 20; i++) {
      dout.writeInt(i);
    }
    FileOutputStream fout = new FileOutputStream("fibonacci.dat");
    try {
      bout.writeTo(fout);
      fout.flush();
    } finally {
      fout.close();
    }
  }
}





new ByteArrayOutputStream(int size)

  
/*
 * Output:
 *  
 */
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class MainClass {
  public static void main(String args[]) throws Exception {
    ByteArrayOutputStream f = new ByteArrayOutputStream(12);
    System.out.println("Please 10 characters and a return");
    while (f.size() != 10) {
      f.write(System.in.read());
    }
    System.out.println("Buffer as a string");
    System.out.println(f.toString());
    System.out.println("Into array");
    byte b[] = f.toByteArray();
    for (int i = 0; i < b.length; i++) {
      System.out.print((char) b[i]);
    }
    System.out.println();
    OutputStream f2 = new FileOutputStream("test.txt");
    f.writeTo(f2);
    f.reset();
    System.out.println("10 characters and a return");
    while (f.size() != 10) {
      f.write(System.in.read());
    }
    System.out.println("Done..");
  }
}