Passing a Java Byte Array to/from Chilkat
This example demonstrates how to pass binary data stored in a Java byte array to/from Chilkat.
import com.chilkatsoft.*;
public class TestBd {
static {
try {
System.loadLibrary("chilkat");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
public static void main(String argv[])
{
CkBinData bd = new CkBinData();
// We have a byte array in Java
byte[] byteArray = {0, 1, 2, 3, 4};
// Copy the bytes into the CkBinData object.
bd.AppendData(byteArray,byteArray.length);
// View the contents of bd in hexadecimal format.
// Output: 0001020304
System.out.println(bd.getEncoded("hex"));
// Append a few more bytes
bd.AppendEncoded("05060708","hex");
// Call GetData to copy the bytes to a new Java byte array object.
byteArray = bd.GetData();
// Print each byte value
for (byte byteVal : byteArray) {
System.out.println(byteVal);
}
System.out.println("----");
// Output is:
// 0
// 1
// 2
// ...
// 8
// You can get a range of bytes by calling GetDataChunk
// GetDataChunk has 0-based indexing. The 1st byte is at index 0.
byteArray = bd.GetDataChunk(2,4);
for (byte byteVal : byteArray) {
System.out.println(byteVal);
}
// Output is:
// 2
// 3
// 4
// 5
}
}