I have a arraylist of Bytes and i am converting them into a byte array.I have used the following method.However it gives me the following error:
E/AndroidRuntime(5228): java.lang.NoClassDefFoundError: com.google.common.primitives.Bytes
ArrayList<Byte> byteArrayList_song=new ArrayList<Byte>();
byte[] bytes_song_byte;
for(int i=0;i<int_arraylist.size();i++)
{
bytes_song_byte=Bytes.toArray(byteArrayList_song);
}
Looks like Google Guava is not on your class path, also you should remove the for loop from the above code, as that is what the Guava function does for you.
ArrayList<Byte> byteArrayList_song = new ArrayList<Byte>();
byte[] bytes_song_byte = Bytes.toArray(byteArrayList_song);
You can do this conversion without external libs
byte[] bytes_song_byte = new byte[byteArrayList_song.size()];
for (int i = 0; i < byteArrayList_song.size(); i++) {
bytes_song_byte[i] = byteArrayList_song.get(i);
}
note that if byteArrayList_song has any null elements this code will throw a NullPointerException
Try the following
ArrayList<Byte> byteArrayList_song=new ArrayList<Byte>();
byte[] bytes_song_byte;
bytes_song_byte=byteArrayList_song.toArray(new Byte[byteArrayList_song.size()]);
Related
I'm having problems downloading files with my company's application, it crashes when I download files over 50mb.
I'm getting the file as an array of native bytes from a WS and then I convert it into an array of Object Byte to serialize it before converting these bytes into the file to download.
This works perfectly with small files but when you are downloading files over 50mb the conversion from bytes[] to Byte[] fails.
This was the code I had:
private RespuestaDescargarDocumento rellenarRespuestaDescarga(byte[] contenido, String nombreDocumento){
Byte[] bytes = ArrayUtils.toObject(contenido);
RespuestaDescargarDocumento respuesta = new RespuestaDescargarDocumento();
respuesta.setContenido(bytes);
respuesta.setNombreDocumento(nombreDocumento);
return respuesta;
}
I take a look what toObject() does and I realised that it is doing a new Byte() every iteration of this loop so if I'm downloading a file of for example 52mb it does 53167398 iterations and for every iteration is creating a new Byte.
public static Byte[] toObject(byte[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_BYTE_OBJECT_ARRAY;
}
final Byte[] result = new Byte[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = new Byte(array[i]);
}
return result;
}
I think this is ridiculous so I looked the way of doing this conversion without this method and found this thread:
how to convert byte[] to Byte[], and the other way around?
And I tried the best answer way like this:
private RespuestaDescargarDocumento rellenarRespuestaDescarga(byte[] contenido, String nombreDocumento) {
//Byte[] bytes = ArrayUtils.toObject(contenido);
Byte[] bytes = byteToByte(contenido);
RespuestaDescargarDocumento respuesta = new RespuestaDescargarDocumento();
respuesta.setContenido(bytes);
respuesta.setNombreDocumento(nombreDocumento);
return respuesta;
}
private Byte[] byteToByte(byte[] array) {
if (array == null || array.length == 0) {
return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;
}
Byte[] bytes;
bytes = new Byte[array.length];
for (int i = 0; i < array.length; i++) {
bytes[i] = array[i];
}
return bytes;
}
And now I can download perfectly that file of 52mb so that worked, or that was I thought, when I tried to download a bigger file of 150mb it crashed again. This time the loop is doing 159551619 iterations.
I'm getting the following error:
java.lang.OutOfMemoryError: Java heap space
In this line:
bytes = new Byte[array.length];
So it doesn't even get the for loop of my function, is like Java can't create an array of this size (159551619). But I found that the maximum size for an array in Java is 2147483647, so it should still work with this.
Am I doing something wrong?
I m trying to get/convert the value of Arraylist in byte[]
below is my code
final ArrayList<Object> imglists = new ArrayList<Object>();
this is my arraylist of Objects in this arraylist m storing the values of images in form of bytes
for (int i=0; i<mPlaylistVideos.size();i++) {
holder.mThumbnailImage.buildDrawingCache();
Bitmap bitmap= holder.mThumbnailImage.getDrawingCache();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bs);
byte[] rough = bs.toByteArray();
imglists.add(i,rough);
}
I m trying to get the specific value from arraylist and store that in byte[]
this is what I was trying to do
byte[] value=imglists.get(2);
I could not find any complete answer to convert Arraylist of Object into byte[]
I know Arraylist doesn't support primitive datatype (i-e byte)
What you are looking for is a List of byte[], something like that:
List<byte[]> imglists = new ArrayList<>();
Then you can simply add your byte array to your List using the add(E) method as next:
imglists.add(bs.toByteArray());
You will then be able to access to a given byte array from its index in the List using the method get(int) as you try to achieve:
// Get the 3th element of my list
byte[] value = imglists.get(2);
You want to convert ArrayList to byte[] ? or Object to byte[]?
I wrote in this way, just simply convert the element in ArrayList into byte[] ,it works!
List<Object> objects = new ArrayList<Object>();
objects.add("HelloWorld".getBytes());
byte[] bytes = (byte[]) objects.get(0);
System.out.println(new String(bytes)); // HelloWorld
I tried to get my byte[] value from JSONObject using following code but I am not getting original byte[] value.
JSONArray jSONArray = jSONObject.getJSONArray(JSONConstant.BYTE_ARRAY_LIST);
int len = jSONArray.length();
for (int i = 0; i < len; i++) {
byte[] b = jSONArray.get(i).toString().getBytes();
//Following line creates pdf file of this byte arry "b"
FileCreator.createPDF(b, "test PDF From Web Resource.pdf");
}
}
Above code creates pdf file but file can not open i.e corrupted file. But, when I use same class and method to create file:
FileCreator.createPDF(b, "test PDF From Web Resource.pdf");
before adding into JSONObject like follwoing:
JSONObject jSONObject = new JSONObject();
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST, bList);
it creates file i.e I can open pdf file and read its content.
What I did wrong to get byte[] from JSONObject so that it is creating corrupted file? Please kindly guide me. And I always welcome to comments. Thank You.
Finally I solved my issue with the help of apache commons library. First I added the following dependency.
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
<type>jar</type>
</dependency>
The technique that I was using previously was wrong for me (Not sure for other). Following is the solution how I solved my problem.
Solution:
I added byte array value previously on JSONObject and stored as String. When I tried to get from JSONObject to my byte array it returned String not my original byte array. And did not get the original byte array even I use following:
byte[] bArray=jSONObject.getString(key).toString().getBytes();
Now,
First I encoded my byte array into string and kept on JSONObject. See below:
byte[] bArray=(myByteArray);
//Following is the code that encoded my byte array and kept on String
String encodedString = org.apache.commons.codec.binary.Base64.encodeBase64String(bArray);
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST , encodedString);
And the code from which I get back my original byte array:
String getBackEncodedString = jSONObject.getString(JSONConstant.BYTE_ARRAY_LIST);
//Following code decodes to encodedString and returns original byte array
byte[] backByte = org.apache.commons.codec.binary.Base64.decodeBase64(getBackEncodedString);
//Creating pdf file of this backByte
FileCreator.createPDF(backByte, "fileAfterJSONObject.pdf");
That's it.
This might be of help for those using Java 8. Make use of java.util.Base64.
Encoding byte array to String :
String encodedString = java.util.Base64.getEncoder().encodeToString(byteArray);
JSONObject.put("encodedString",encodedString);
Decode byte array from String :
String encodedString = (String) JSONObject.get("encodedString");
byte[] byteArray = java.util.Base64.getDecoder().decode(encodedString);
For tests example(com.fasterxml.jackson used):
byte[] bytes = "pdf_report".getBytes("UTF-8");
Mockito.when(reportService.createPackageInvoice(Mockito.any(String.class))).thenReturn(bytes);
String jStr = new ObjectMapper().writeValueAsString(bytes).replaceAll("\\\"", ""); // return string with a '\"' escape...
mockMvc.perform(get("/api/getReport").param("someparam", "222"))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
...
.andExpect(jsonPath("$.content", is(jStr)))
;
When inserting a byte array into a JSONObject the toString() method is invoked.
public static void main(String... args) throws JSONException{
JSONObject o = new JSONObject();
byte[] b = "hello".getBytes();
o.put("A", b);
System.out.println(o.get("A"));
}
Example output:
[B#1bd8c6e
so you have to store it in a way that you can parse the String into the original datatype.
byteArray = new byte[10000];
-- some code here ----
byteBuffer.wrap(byteArray);
for (int i=0; byteBuffer.hasRemaining(); i++)
{
shortArray[i] = byteBuffer.getShort();
System.out.println(shortArray[i]);
}
The byteBuffer.hasRemaining() gets flagged with a NullPointerException although I have provided it with a backing array.
What is the problem here?
Please, check how you initialize byteBuffer it should be something like this since wrap is a static method
byte[] byteArray = new byte[10000];
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
The code seems OK. I suspect this is (due to some bug) because byteBuffer variable = null
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Creating a byte[] from a List<Byte>
I have List list. How to get byte[] ( subarray of list ) from startIndex to endIndex id list ?
List<Byte> theList= new ArrayList<Byte>();
Byte[] your_bytes = theList.subList(startIndex,endIndex).toArray(new Byte[0]);
If finally you need to work with byte (the primitive) then I recommend Apache Commons Collections toPrimitive utility
byte[] your_primitive_bytes = ArrayUtils.toPrimitive(your_bytes);
For most cases you certainly can get by with Byte (object).
ArrayList<Byte> list = new ArrayList<Byte>();
ArrayList<Byte> subList = (ArrayList<Byte>) list.subList(fromIndex, toIndex); //(0,5)
Byte[] array = (Byte[]) subList.toArray();
Well, since the original question actually asks for a sublist containing a byte[] (not Byte[]) here goes:
List<Byte> byteList = .... some pre-populated list
int start = 5;
int end = 10;
byte[] bytes = new byte[end-start]; // OP explicitly asks for byte[] (unless it's a typo)
for (int i = start; i < end; i++) {
bytes[i-start] = byteList.get(i).byteValue();
}
If you need byte[]:
byte[] byteArray = ArrayUtils.toPrimitive(list.subList(startIndex, endIndex).toArray(new Byte[0]));
ArrayUtils.toPrimitive