[英]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.