Exception in thread "main" javax.imageio.IIOException: Can't read input file!

1,770 阅读2分钟

背景概述:最近在写连锁超市的项目其中遇到了很多坑,其中接下来就是其中一个 ,望道友们有帮助

报错提示

Exception in thread "main" javax.imageio.IIOException: Can't read input file!

写的程序如下 :

 public static void main(String[] args) throws IOException {
   
        String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        Thumbnails.of(new File("D:\\zhangxiyu.jpg"))
                .size(200,200).watermark(Positions.BOTTOM_RIGHT,
                ImageIO.read(new File(basePath+"/watermark.jpg")),0.25f).outputQuality(0.8f)
                .toFile("D:\\zhangxiyunew.jpg");
    }

解决 问题

  • 查阅很多资料后发现问题如下
 在java中获取文件路径的时候,有时候会获取到空格,但是在中文编码环境下,空格会变成“%20”从而使得路径错误
  • 解决方法

1:) TestURL().class.getResource("").getPath()或TestURL().class.getResource("").getFile()获得的路径,不能被FileReader()和FileWriter()直接应用。原因是URL对空格,特殊字符(%,#,[]等)和中文进行了编码处理。 例如:空格变为%20。有解决方法(1),使用repaceAll("%20",'')替换后,只能解决空格问题。但是路径中包含%和中文就不行了。

2:) 使用URLDecoder.decode(str,"UTF-8")解码,但是只能解决一部分,若路径中含有+,也是不能解决的,原因是URL并不是完全用URLEncoder.encode(str,"UTF-8")编码的,+号被解码后,却变成了空格。

3:) 可以解决所有的问题,用TestURL().class.getResource("").toURI().getPath(),但是需要处理URISyntaxException异常,比较麻烦点。

  • 总结解决方法
  path=URLDecoder.decode(path,"utf-8");//关键啊 ! 
  • 如上方法是把空格给转化了 就可以了

更改代码如下

   private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

  static{
        try {
              basePath = URLDecoder.decode(basePath,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
全部代码为
    //通过线程的反向推导出calsspath的路径
    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

  static{
        try {
              basePath = URLDecoder.decode(basePath,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {

        String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        Thumbnails.of(new File("D:\\zhangxiyu.jpg"))
                .size(200,200).watermark(Positions.BOTTOM_RIGHT,
                ImageIO.read(new File(basePath+"/watermark.jpg")),0.25f).outputQuality(0.8f)
                .toFile("D:\\zhangxiyunew.jpg");
    }
}
资料参考链接为
希冀可以帮得上各位道友,加油道友们!!!