因为场景需求,要从前置机连接的另一台数据服务器上通过FTP获取大量图片转成一个pdf并打印。因此需要获取图片的InputStream。
因为没接触过所以开始使用的常规方法:(如下)
BufferedImage img =null;
File img = new File("ftp://ftpuser:666@192.168.55.110/IMG/123456789.JPG")
InputStream is=new FileInputStream(img);
img = ImageIO.read(is);
结果程序报错 提示java.io.FileNotFoundException:文件名、目录名或卷标语法不正确
原因是虽然连接了ftp但还是相当于通过网络获取,所以file就无法通过路径获取
因此用了如下代码替换
String imagePath ="ftp://ftpuser:666@192.168.55.110/IMG/123456789.JPG";
BufferedImage img =null;
URL url =new URL(imagePath);
URLConnection connect = url.openConnection();
connect.setDoInput(true);
InputStream input = connect.getInputStream();
img = ImageIO.read(input);
完美解决,虽然是个小问题,但是在网上找了很久也没找到解决办法。大多数人报这个错是因为路径语法不对。
最后是通过看了git上一段c#代码(如下) 才理解了是通过网络请求的方法获取的流
Image img = Image.FromStream(System.Net.WebRequest.Create(picPath).GetResponse().GetResponseStream());
自己学习过程中一点积累,希望能对你有些帮助。