Convert ByteArrayOutputStream to int values - java

I am constantly trying to convert a ByteArrayOutputStream to int values.
I am recording an Audio with microphone and writing it to out = new ByteArrayOutputStream() like so:
out.write(buffer, 0, count);
byte audio[] = out.toByteArray();
When I print this I get these : [B#3456337e
How do I convert these to integer numbers.
Please Help, Thanks

There is no standard way to do it because actually it depends on what kind of bytes you have but, as it is an audio source, I think you can do it like that :
IntBuffer intBuf =
ByteBuffer.wrap(byteArray)
.order(ByteOrder.BIG_ENDIAN) //or try ByteOrder.LITTLE_ENDIAN
.asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);
//The result you want is "array"
I hope it will help you.

Convert it to an array, wrap the array in a ByteArrayInputStream, wrap that in a DataInputStream, and use readInt().

Try the following -
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataInputStream dataIs = new DataInputStream
(new ByteArrayInputStream(out.toByteArray());
// available stream to be read
while(dataIs.available()>0)
{
int k = dataIs.readInt();
// print int
System.out.print(k+" ");
}

Related

gzip: Inflate float array in java

I am trying to figure out a way to inflate/deflate an array of floats in java.
My code to deflate looks like this, which seems to work fine.
List<Float> floats = ...;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
ObjectOutputStream objectOut = new ObjectOutputStream(gzipOut);
objectOut.writeObject(floats.toArray(new Float[0]));
return baos.toByteArray();
I am having issues with inflating the byte array again back to a float[] array.
Below is one of my attempts, which fails (it even generates NaN floats)
byte[] bytes =....
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
GZIPInputStream gzipIn = new GZIPInputStream(bais);
ObjectInputStream objectIn = new ObjectInputStream(gzipIn);
List<Float> floats = new ArrayList<>()
byte[] buffer = new byte[4]
while (gzipIn.read(buffer) >= 0) {
Float f = ByteBuffer.wrap(buffer).float
floats.add(f)
}
return floats
I am be able to use any other classes - I just am not able to block as this would be running inside a non blocking event driven server.
You're using different calls - you're calling writeObject in the writing part, then assuming that you can just read 4 bytes at a time in the reading part.
Why not just use:
Float[] floats = (Float[]) objectIn.readObject();
? That would match your writing code. You can then wrap the array in a list if you want to.

ByteArrayOutputStream.toString() generating extra characters

I have the following code:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int size = 4096;
byte[] bytes = new byte[size];
while (is.read(bytes, 0, size) != -1)
{
baos.write(bytes);
baos.flush();
}
When I do:
String s = baos.toString();
I get \u0000-s appended to my string. So, if my character data is only X bytes out of Y, the Y-Z will get prefilled with \u0000 making it impossible to check for equals. What am I doing wrong here? How should I be converting the bytes to a String in this case?
The entire array (all 4096 bytes) is be written to the output - arrays have no idea of how much "useful data" they contain!
Store how much was read into a variable (InputStream.read returns a useful number) and specify that to the appropriate OutputStream.write overload to only write a portion (that which contains the useful data) of the array.
While the above change should "fix" the problem, it is generally recommended to use the string<->byte[] conversion forms that take in an explicit character set.
You should only be writing as much data as you are reading in each time through the loop:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int size;
byte[] bytes = new byte[4096];
while (size = is.read(bytes, 0, bytes.length) != -1)
{
baos.write(bytes, 0, size);
}
baos.flush();
String s = baos.toString();
You might consider specifying a specific character set for converting the bytes to a String. The no-arg toString() method uses the platform default encoding.
new String(baos.toByteArray(), 0, strLen, encoding)

Create a ArrayList of byte Array in Android

I want to read bytes from httpresponse coming from server continuosly into an array.
I'm creating a byte array with a maximum size of 2048.
So, I wanted to create a dynamically increasing array and I found that ArrayList is the solution.
How can i overcome this solution?
Any help would be appreciated lot
You can use a ByteArrayOutputStream to accumulate the bytes as you read them from the server. I would not use an ArrayList<Byte> because it requires boxing every byte value in a Byte.
When you want to access the bytes that have been accumulated, just call toByteArray() on the ByteArrayOutputStream.
You can have an array of byte like:
List<Byte> arrays = new ArrayList<Byte>();
To convert it back to arrays
Byte[] soundBytes = arrays.toArray(new Byte[arrays.size()]);
- You can also use ByteArrayInputStream and ByteArrayOutputStream.
Eg:
InputStream inputStream = socket.getInputStream();
// read from the stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] content = new byte[ 2048 ];
int bytesRead = -1;
while( ( bytesRead = inputStream.read( content ) ) != -1 ) {
baos.write( content, 0, bytesRead );
} // while
// now, as you have baos in hand, I don't think you still need a bais instance
// but, to make it complete,
// now you can generate byte array input stream as below
ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() );

Saving short[] in java (android) with low cpu and space

while streaming music i'm getting pcm data as type short[] and i want to save it to file in my android device so i can play it again later (using AudioTrack). i wan't the store of the music to be efficent in memory and cpu.
how to save short[] to file cause i dont see any function in.write(short[])?
how can i decrease the space\cpu for saving this file?
Wrap your FileOutputStream with DataOutputStream:
DataOutputStream doStream = new DataOutputStream(new BufferedOutputStream(fileOutputStream));
doStream.writeInt(numberArray.length); //Save size
for (int i=0;i<numberArray.length;i++) {
doStream.writeShort(numberArray[i]); //Save each number
}
Same way for reading it back:
DataInputStream diStream = new DataInputStream(new BufferedInputStream(fileInputStream));
int size = diStream.readInt(); //Read size
short[] data = new short[size]; //Create new array with required length
for (int i=0;i<size;i++) {
data[i] = diStream.readShort(); //Read each number
}
Without any encoding to MP3 or similar you can always do like this.
short[] sound = ...;
ByteBuffer byteMyShorts = ByteBuffer.allocate(sound.length * 2);
ShortBuffer shortBytes = byteMyShorts.asShortBuffer();
shortBytes.put(sound);
byteMyShorts.flip();
// byteMyShorts.array() now contains your short[] array as an
// array of bytes.

FileInputStream to byte array in Android application

I have a FileInputStream created using Context.openFileInput(). I now want to convert the file into a byte array.
Unfortunately, I can't determine the size of the byte array required for FileInputStream.read(byte[]). The available() method doesn't work, and I can't create a File to check it's length using the specific pathname, probably because the path is inaccessible to non-root users.
I read about ByteArrayOutputStream, and it seems to dynamically adjust the byte array size to fit, but I can't get how to read from the FileInputStream to write to the ByteArrayOutputStream.
This should work.
InputStream is = Context.openFileInput(someFileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
This is the easiest way
FileInputStream fis = openFileInput(fileName);
byte[] buffer = new byte[(int) fis.getChannel().size()];
fis.read(buffer);
You can pre-allocate the byte array using
int size = context.getFileStreamPath(filename).length();
This way, you will avoid allocating memory chunks every time your ByteArrayOutputStream fills up.
For the method to work on any device and aplication you just need to replace:
InputStream is = Context.getContentResolver().openInputStream(yourFileURi);
This way you can encode external files as well.

Categories