1 Reply Latest reply on Jan 3, 2009 10:59 PM by einundswanzig

    Read large file in chucks

    einundswanzig
      I want to read a potential large file by using the FileStream.readBytes function. But every example in the net take a really naive approach by providing the readBytes function with the File.size or FileStream.bytesAvailable length to read the entire file. So i was trying to read the file using:

      var block:uint = 1024 * 512; // 512 kbs
      var s:MD5Stream = new MD5Stream();
      var buffer:ByteArray = new ByteArray();
      var stream:FileStream = new FileStream();

      while (stream.bytesAvailable) {
      if (stream.bytesAvailable > block) {
      stream.readBytes(buffer, 0, block);
      } else {
      stream.readBytes(buffer, 0, stream.bytesAvailable);
      }
      //md5stream.update(buffer);
      }

      This with the purpose of generate the md5 hash but at the end the md5stream gives me a different sum than that if i just pass the entire stream bytes, also when i pass the entire stream bytes the sum is correct. Am i missing something? Is this the correct way of reading a file in blocks?
        • 1. Re: Read large file in chucks
          einundswanzig Level 1
          Ok i found the solution, and as usual the problem was in the code, the readBytes is not replacing the buffer instance but just the block that needs to be fill so the buffer were already fill with the last bytes and since the last loop pass usually is smaller it still contains the bytes of the last pass, so this fix the problem:

          var block:uint = 1024 * 512; // 512 kbs
          var s:MD5Stream = new MD5Stream();
          var buffer:ByteArray = new ByteArray();
          var stream:FileStream = new FileStream();
          stream.open(o, FileMode.READ);

          while (stream.bytesAvailable) {
          buffer = new ByteArray();
          block = (stream.bytesAvailable > block) ? block : stream.bytesAvailable;
          stream.readBytes(buffer, 0, block);
          s.update(buffer);
          }

          Yahoo!