Вопрос

I'm trying to read the first 8192 bytes from a file and run those bytes through a method that returns a boolean.

That boolean tells me if the file is of a particular type.

If the method returns true on the bytes for the file type I then want to get the remaining bytes and run them through a different method. If false, run the remaining bytes through a different method.

I'm trying to use mark, but having no success.

private final void handleFile(InputStream inputStream) {

   BufferedInputStream bis = new BufferedInputStream(inputStream);
   bis.mark(8192);
   byte[] startingBytes = inputStreamToByteArray(bis);

   if(startingBytes.length == 0) { return; }

   byte[] finalBytes;
   if(isFileType(startingBytes)) {
      bis.reset();
      finalBytes = inputStreamToByteArray(bis);
      methodForFinalBytes(finalBytes);
   } else {
      // Do other stuff;
   }
}

private byte[] inputStreamToByteArray(InputStream inputStream) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   byte[] buffer = new byte[8192];

   try {
      while(inputStream.read(buffer) != -1) {
          baos.write(buffer);
      }
   } catch(IOException ioe) {
      ioe.printStackTrace();
   }

return baos.toByteArray();
}

Problem is picking up where I left off while also keeping byte array in chunks (for processing against large files). Also, I'm only getting 8192 bytes returned and not the remaining.

Any suggestions?

Это было полезно?

Решение

First, it looks like inputSTreamToByteArray()is reading the entire stream until end of file, not just the first 8192 bytes. You probably want to read the first 8192 bytes separately first.

Second, do you want to re-read those bytes again? If not, I'm not sure if you need to mark/reset. (Especially since you still have the byte array )

The code below reads the first 8192 bytes first, then decides what to do:

byte[] header = new byte[8192];
//reads entire array or until EOF whichever is first
bis.read(header);

if(isFileType(header)) {
  byte[] finalBytes = inputStreamToByteArray(bis);
  methodForFinalBytes(finalBytes);
} else {
  // Do other stuff;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top