背景概述:最近在写连锁超市的项目其中遇到了不少坑,其中接下来就是其中一个 ,望道友们有帮助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");
}
}
复制代码