简体   繁体   English

无法弄清楚为什么IO文件的索引超出范围

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

This program reads from card.raw and creates a jpg. 该程序从card.raw读取并创建一个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. 这意味着每次执行时,您都试图从数组中写入512个字节,而跳过513个字节,但该数组只有512个字节长。 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. 从513字节开始,它将写入512字节的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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