我用记事本打开了读取的图片和生成的图片,比较后发现,只是开头部分有几处不一样,我弄不明白是什么原因导致的,请大拿指点下,源代码如下:
public static void main(String[] args){
   FileInputStream fis=null;
   FileOutputStream fos=null;
   try{
       fis=new FileInputStream("E:\\资料\\1.jpg");
       fos=new FileOutputStream("E:\\资料\\new.jpg",true);
       while(fis.read()!=-1){
          byte[] b=new byte[1024];
          fis.read(b);
          fos.write(b);
       }
      }catch(Exception e){
          e.printStack();
      }
}
补充:源文件大小为62.1KB,读取后为63KB。

解决方案 »

  1.   

    问题1 : byte[]写在while里,会多次分配空间,浪费
    问题2:刚开始在while里会read一下,这样就会丢掉前面的byte会,所以会看到文件开头少东西
    问题3:write方法直接去写了,而没有去管读到的是否是1024个byte,最后读到的字节少于1024而直接往文件中写,就导致的新文件比原文件大。
    问题4:文件流的关闭要注意一下 public static void main(String[] args) throws IOException {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream("1.jpg");
                fos = new FileOutputStream("new.jpg", false);
                byte[] b = new byte[1024];
                int count = fis.read(b);
                while (count > 0) {
                    fos.write(b, 0, count);
                    count = fis.read(b);
                }
                fos.flush();        } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            }
        }