Convert ArrayList to byte array - java

I have a code where I am converting array list to byte array and then saving that byte array as a BLOB in MySQL database. Below is code:-
Object temp = attributes.get(columnName);
if (temp instanceof List && temp != null) {
List extraAttributes = (ArrayList) temp;
resultStmt.setBytes(currentIndex, createByteArray(extraAttributes));
The method createByteArray is defined as below:
private byte [] createByteArray( Object obj)
{
byte [] bArray = null;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream objOstream = new ObjectOutputStream(baos);
objOstream.writeObject(obj);
bArray = baos.toByteArray();
}
catch (Exception e)
{
TraceDbLog.writeError("Problem in createByteArray", e);
}
return bArray;
}
Well the above code was written earlier for writing HashMap to BLOB i am using same for converting ArrayList if HashMap to BLOB.
The problem which is occurring in read code when i am reading the blob.
private Object readBytes (ResultSet rs, String columnName)
throws SQLException
{
ObjectInputStream ois = null;
byte [] newArray;
Object obj = null;
try
{
newArray = rs.getBytes(columnName);
ois = new ObjectInputStream (new ByteArrayInputStream(newArray));
obj = ois.readObject ();
}
In the read part the object is not coming as arrayList of hasMap and in debug perspective in eclipse eclipse is also not able to inspect the object which is coming.
I have also tried typecasting the object to List but still no success in getting the right response.
Please tell me whether there is any flaw in reading/writing the above BLOB.

I have added sample coding for convert ArrayList to byte[].
One reasonable way would be to use UTF-8 encoding like DataOutputStream does for each string in the list. For a string it writes 2 bytes for the length of the UTF-8 encoding followed by the UTF-8 bytes.
This would be portable if you're not using Java on the other end. Here's an example of encoding and decoding an ArrayList:
// example input list
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (String element : list) {
out.writeUTF(element);
}
byte[] bytes = baos.toByteArray();
// read from byte array
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
String element = in.readUTF();
System.out.println(element);
}

The easiest way is to convert it to json string and then to bytes
Gson gson = new Gson();
Type type = new TypeToken<List<Alarm>>() {}.getType();
String json = gson.toJson(list, type);
byte[] bytes = json.getBytes();

Related

Convert blob to string to to create a json object and then change the string back to blob

My requirement is to convert the blob in a database field to string to create a json object. I have achieved that.
Now, I need to convert this string back to blob. I wrote the below code. But, it does not work. In my instance, I have the word document stored as blob. I converted it to string but when I converted the string to blob, the document does not open properly.
Please let me know a way to convert the string back to blob.
DocumentTemplateKey documentTemplateKey = new DocumentTemplateKey();
documentTemplateKey.documentTemplateID = "XX";
DocumentTemplateDtls documentTemplateDtls = DocumentTemplateFactory.newInstance().read(documentTemplateKey);
byte[] blobAsBytes = documentTemplateDtls.contents.copyBytes();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(blobAsBytes, 0, blobAsBytes.length);
String pdfBase64String =
org.apache.commons.codec.binary.StringUtils.newStringUtf8(org.apache.
commons.codec.binary.Base64.encodeBase64(bos.toByteArray()));
OutputStreamWriter out = new OutputStreamWriter(System.out);
JsonWriter writer = new JsonWriter(out);
//set indentation for pretty print
writer.setIndent("\t");
//start writing
writer.beginObject(); //{
writer.name("blob").value(pdfBase64String);
byte[] stringAsBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(pdfBase64String);
Blob blob = new Blob(stringAsBytes);
documentTemplateDtls.contents = blob;
documentTemplateDtls.documentTemplateID = "XX12";
documentTemplateDtls.name = "XX12";
DocumentTemplateFactory.newInstance().insert(documentTemplateDtls);
writer.endObject();
writer.flush();
//close writer
writer.close();
Here's your problem:
byte[] stringAsBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(pdfBase64String);
You're getting the bytes of your base64 string, but you ought to be putting it through a base64 decoder.

How to put byte stream image data into JSON object?

I want to put multiple images in JSON object using byte stream format, i wrote the following code.
FileInputStream fin = new FileInputStream(pathToImages+"//"+"01.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
bout.write(encoder.encode(contents).getBytes());
}
JsonObject myObj = new JsonObject();
I want to put encoded byte stream in myObj,but dont know how to do it.
Thanks
JSONObject myObj = new JSONObject();
myObj.put("1",encoder.encode(contents).getBytes());
I think this will work.
Assuming you are using Java 8, and the javax.json package:
Path path = Paths.get(pathToImages, "01.jpg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream(
(int) (Files.size(path) * 4 / 3 + 4));
try (OutputStream base64Stream = Base64.getEncoder().wrap(bytes)) {
Files.copy(path, base64Stream);
}
String base64 = bytes.toString("US-ASCII");
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("data", base64);
JsonObject myObj = builder.build();

How to read an array of bytes from a file using datainput stream, and print the array of bytes in java

I have stored an array of bytes byte[] testByte; testByte = new byte[]{3,4} into a file, now I need to read from the file and assign the array of bytes to a variable and print it.
I have done the following code,but i am not able to print the array of bytes
public static void main(String[] args) throws IOException {
InputStream is = null;
DataInputStream dis = null;
try{
// create input stream from file input stream
is = new FileInputStream("c:\\test.txt");
// create data input stream
dis = new DataInputStream(is);
// count the available bytes form the input stream
int count = is.available();
// create buffer
byte[] bs = new byte[count];
// read data into buffer
dis.read(bs);
}
Now how to store the contents in the buffer bs into an array.
Please help to resolve this
You can store the content of bs buffer using new String
public static void main(String[] args) throws IOException {
InputStream is = null;
DataInputStream dis = null;
int count = 0;
byte[] bs = null;
String content = "";
try{
is = new FileInputStream("C:\\test.txt");
dis = new DataInputStream(is);
count = is.available();
bs = new byte[count];
dis.read(bs);
// here is a variable that contains the buffer content as a String
content = new String(bs);
} catch (IOException e) {
} finally {
is.close();
dis.close();
}
System.out.println(content);
}
Edit(Answer to comment):
Well, when we create the new String() we instantiate a new String with the byte[] value.
But, as you already have an array of bytes, then you can store the value of the String object on it again using:
bs = content.getBytes();
In advance, don't worry if the print of the bytes are different, like
[B#199c55a
[B#faa824
It's just a name given to the object, but the value is the same on both.

Object Deserialization- to get back int array from serialized Object

int[] myIntArray;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new DeflaterOutputStream(byteArrayOutputStream));
objectOutputStream.writeObject(myIntArray);
Now,ObjectOutputStream takes The object and directly serializes it. DeflaterOutputStream compresses the serialized result, then the compressed result is stored in a ByteArrayOutputStream
Can Someone tell me How to Deserialize and get back my original int array back?
Plz Share the coding?
objectOutputStream.close();
byte[] serialized = byteArrayOutputStream.getBytes();
// and then read back using symmetric constructs as when writing, but using
// input streams instead of output streams:
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serialized);
ObjectInputStream objectInputStream =
new ObjectInputStream(new InflaterInputStream(byteArrayInputStream));
int[] myDesererializedIntArray = (int[]) objectInputStream.readObject();

Convert byte [] to ArrayList<Object>

I have a byte[] that i obtained using Object ArrayList<Obj>
Can anyone tell me how to convert my byte[] to Object ArrayList?
Coveting ArrayList like this:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
oos = new ObjectOutputStream(bos);
oos.writeObject(mArrayList);//mArrayList is the array to convert
byte[] buff = bos.toByteArray();
Now you've given us the information about how you did the conversion one way... you need:
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
try {
#SuppressWarnings("unchecked")
ArrayList<Object> list = (ArrayList<Object>) ois.readObject();
...
} finally {
ois.close();
}
I'm going to go with the obvious answer here...
for(byte b : bytearray) {
arraylist.add(new Byte(b));
}

Categories

Resources