Save string to byte array and read back in Java

Description

The following code shows how to save string to byte array and read back.

Example


/*from   w  w  w  . java  2s  .co  m*/
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;
    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));
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip