[英]Can't figure out why index is out of bound for IO file
该程序从card.raw读取并创建一个jpg。 我可以成功创建第一个图像,但是我似乎无法弄清楚为什么我对第二个图像的索引超出了界限错误
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) {
不能弄清楚为什么我在下面的行中超出索引的错误
os2.write(fileContent2,513,512);
}
fs2.close();
os2.close();
}
catch(IOException ioe) {
System.out.println("Error " + ioe.getMessage());
}
}
}
这是您选择字节数组的任意大小(512)且图像文件大小必须大于512的方式的正常现象。
你写了
os2.write(fileContent2,513,512);
这意味着每次执行时,您都试图从数组中写入512个字节,而跳过513个字节,但该数组只有512个字节长。 所以它不合适。
尝试这个..
File file = new File("path to card.raw");
long len = file.length();
byte[] fileContent = new byte[len];
fs2.read(fileContent);
之后使用
os2.write(fileContent2,513,512);
循环外仅一次。 从513字节开始,它将写入512字节的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.