2016-02-07 21 views
0

该程序从card.raw读取并创建一个jpg。我可以成功地创建了第一个形象,但我似乎无法找出原因,我得到一个索引出界误差的第二图像不知道为什么索引超出了IO文件的限制

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()); 
    } 
} 
} 

回答

0

线这是您选择的字节数组(512)和图像文件大小必须大于512

+0

那你能否给我一些方向来获得第二张图片呢? – SteelFox

+0

以3000为例,并测试您的程序。然后,如果它可以工作,可以通过在文件中使用length()方法以更简洁的方式获得图像文件的大小。 – Smallware

+0

好的谢谢:) – SteelFox

0

你写

的任意大小的方式正常
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字节的数据。

+0

你能推荐一个更好的方式来写我吗?我是编程新手 – SteelFox

+0

将偏移量设置为0(第二个参数) –

+0

这只会让我再次获得第一个图像吗?我想获取card.raw中的第二张图片 – SteelFox

相关问题