How do I create a Java byte array containing the last x bytes of an inputstream?

In Java, I have an inputstream and want a byte array containing the last x bytes. What is the best way to do this?
rubixcube5Asked:
Who is Participating?
 
HegemonConnect With a Mentor Commented:
Have another array (anotherArray) of the same size and copy the content of the first array into it before each read() call.
The border case: if your read() returns -1 or 0, anotherArray contains the last x bytes.
Otherwise, if read() returns 0 < n < x, the last n bytes of x are stored in the first array from 0 onwards, up to n-1. The first x-n elements are at the end of anotherArray.
0
 
mrdodgerCommented:
Byte [] ba = new Byte[]
0
 
rubixcube5Author Commented:
hahahahaha! you've declared a byte array but that's it! it's empty! where is the inputstream?
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
HegemonCommented:
byte[] array = new byte[x];
inputStream.read (array, offset, x);

0
 
rubixcube5Author Commented:
Hegemon, I could use your solution where offset = length of bytes in the inputStream - x.
But then I have to read in the inputstream twice, once to get the length and then again to get the last x bytes.
What is a more efficient solution?
0
 
Gurvinder Pal SinghCommented:
you can use StringWriter to convert InputStream to String first, then you can get the last x number of bytes from String into byte Array

http://stackoverflow.com/questions/309424/in-java-how-do-a-read-convert-an-inputstream-in-to-a-string
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#getBytes%28%29

but i think even if here InputStream  is read once, the solution proposed by @Hegemon #33745896 is the best possible solution
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.