菜鸟级h5 2017-08-14 12:00 采纳率: 40%
浏览 1064
已采纳

文件读写流读写图片异常

public class FileDemo {

public static void main(String[] args) {
    try {
        File f = new File("e:/e/123456.jpg");
        FileInputStream ff = new FileInputStream(f);
        BufferedInputStream bf = new BufferedInputStream(ff);
        FileOutputStream fo = new FileOutputStream(f.getAbsolutePath());
        BufferedOutputStream bo = new BufferedOutputStream(fo);
        byte[]b=new byte[1024];
        int len=0;
        while((len=bf.read(b))!=-1) {
            bo.write(b);
            bo.flush();
        }
        bo.close();
        fo.close();
        bf.close();
        ff.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}
我用这个程序读来一个图片,然后发现图片说明
就是这样的。请问我的程序哪里有问题?谢谢解答

  • 写回答

2条回答 默认 最新

  • 鼠晓 博客专家认证 2017-08-15 01:19
    关注

    我把你的代码调试了一下发现,,这句代码有很大问题

      FileOutputStream fo = new FileOutputStream(f.getAbsolutePath());
    
    

    输出流会把文件清空,,,也就是你这句话会把 你的 f文件清空,,,可以找一个文本文件测试一下下面代码:

                            File f = new File("G:/test.txt");
                FileInputStream ff = new FileInputStream(f);
                BufferedInputStream bf = new BufferedInputStream(ff);
                File f2 = new File("G:/test.txt");
                FileOutputStream fo = new FileOutputStream(f2);
    

    通过源码发现,,确实是要清空的,,源码中有个是否追加的参数,,默认是falst(不追加,清空)
    图片说明
    图片说明

    你需要修改路径,,如下:

     public static void main(String[] args) {
        try {
            File f = new File("e:/e/123456.jpg");
            FileInputStream ff = new FileInputStream(f);
            BufferedInputStream bf = new BufferedInputStream(ff);
            FileOutputStream fo = new FileOutputStream("e:/e/10086.jpg");
            BufferedOutputStream bo = new BufferedOutputStream(fo);
            byte[]b=new byte[1024];
            int len=0;
            while((len=bf.read(b))!=-1) {
                bo.write(b);
                bo.flush();
            }
            bo.close();
            fo.close();
            bf.close();
            ff.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    }
    

    如上代码,,完美执行,,,有问题还可以追问,,,木有问题,请采纳

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效