简体   繁体   中英

Can't figure out why index is out of bound for IO file

This program reads from card.raw and creates a jpg. I could create the first image sucessfully, but I can't seem to figure out why i get an index out of bound error for the second image

  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.BufferedInputStream;
  import java.io.BufferedOutputStream;

  public class Recoverytst {
     public static void main (String[] args) throws IOException {
        try {
           FileInputStream fs = new FileInputStream("card.raw");
           FileOutputStream os = new FileOutputStream("1.jpg");
           byte[] fileContent = new byte[512];

           while (fs.read(fileContent) != -1) {
           os.write(fileContent);
        }
          fs.close();
          os.close();
    }
        catch(IOException ioe) {
           System.out.println("Error " + ioe.getMessage());
   }

try {
  FileInputStream fs2 = new FileInputStream("card.raw");
  FileOutputStream os2 = new FileOutputStream("2.jpg");
  byte[] fileContent2 = new byte[512];

  while (fs2.read(fileContent2) != -1) {

Cant figure out why i get index out of bound error over here for the line below

    os2.write(fileContent2,513,512);
  }
  fs2.close();
  os2.close();
}
catch(IOException ioe) {
  System.out.println("Error " + ioe.getMessage());
  }
}
}

这是您选择字节数组的任意大小(512)且图像文件大小必须大于512的方式的正常现象。

You wrote

os2.write(fileContent2,513,512);

What this means is every time it executes, you are trying to write 512 bytes from the array skipping 513 bytes but the array is only 512 bytes long. So it won't fit.

Try this..

File file = new File("path to card.raw");
long len = file.length();

byte[] fileContent = new byte[len];
fs2.read(fileContent);

After that use

os2.write(fileContent2,513,512);

out side the loop only once. It will write 512 bytes of data starting from the 513 byte.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM