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

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

报错提示

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",'')替换后,只能解决空格问题。可是路径中包含%和中文就不行了。bash

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

3:) 能够解决全部的问题,用TestURL().class.getResource("").toURI().getPath(),可是须要处理URISyntaxException异常,比较麻烦点。spa

  • 总结解决方法
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");
    }
}
复制代码
资料参考连接为
希冀能够帮得上各位道友,加油道友们!!!
相关文章
相关标签/搜索