我的应用程序在jpegs中读取的问题并将其显示在jlabel上(这些是图书的图片) 与本地版本一起使用时一切正常,例如从C盘读取,但是一旦我尝试在互联网上尝试这样做,就会出现问题,我试过没有成功纠正 脚本 如果jpeg不在URL的末尾,我会收到以下错误
javax.imageio.IIOException: Can't get input stream from URL!
在从本地驱动器读取的版本中,我检测文件是否存在并克服了这个问题但是我已经尝试了很多想法,我根本无法找到如何检测到jpeg不存在! 请帮助一下 这是代码的两个版本
从本地驱动器C读取
private void showcover() {
String stockPic;
String partofISBN;
String completeurl;
jButton9.setVisible(true);
stockPic = jTextField1.getText();// get the current isbn
partofISBN = stockPic.substring(0, 7); // get first 7 numbers
String picUrl;
stockPic = stockPic + localNumber + ".jpg";
picUrl = partofISBN + "\\" + stockPic;
completeurl = "C:\\Apicture\\" + picUrl;
File pf = new File(completeurl);
if (!pf.exists()) {
jLabel9.setIcon(new ImageIcon("C:\\Apicture\\" + picUrl));
jLabel9.setIcon(new ImageIcon("C:\\Apicture\\nojpegs.jpg"));
jLabel9.setText("NO Jpeg");
}
jLabel9.setIcon(new ImageIcon(completeurl));
}
适应从网址读取
URL url;
url = new URL("http://ebid.s3.amazonaws.com/upload_big/9/1/1/1401018425-17770-385.jpg");
Image image = null;
try {
image = ImageIO.read(url);
} catch (IOException ex) {
Logger.getLogger(baseframe.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(baseframe.class.getName()).log(Level.SEVERE, null, ex);
}
答案 0 :(得分:0)
javax.imageio.IIOException
表示您没有获得图片。
因此,请在catch(IOException )
块中添加更多代码以故障转移到备用网址/磁盘。
答案 1 :(得分:0)
读取未找到的http HEAD请求和响应代码404。 Http是你的朋友。
在获取资源之前找出资源。
答案 2 :(得分:0)
您可能想查看我刚才提供的答案:I can't download a specific image using java code
似乎亚马逊也在检查您的用户代理,因此您可能需要在代码的开头添加类似的内容:
System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");
编辑:“代码开头的 ”在创建任何与网址相关的对象之前,实际上意味着“”。我的意思是,我不想参考您发布的代码,而是整个应用程序。
答案 3 :(得分:0)
使用此:
URL url;
url = new URL("http://ebid.s3.amazonaws.com/upload_big/9/1/1/1401018425-17770-385.jpg");
url.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");
Image image = null;
try {
image = ImageIO.read(url);
} catch (IOException ex) {
Logger.getLogger(baseframe.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(baseframe.class.getName()).log(Level.SEVERE, null, ex);
}