网络图片抓下来不完整,打不开,因为此文件已损坏或过大
rt
我觉得大概原因是抓的不完整,请问怎么检验下载的图片是完整的
大概代码如下:
public boolean connect(String address){
boolean isConnected = true;
try {
url = new URL(address);
} catch (MalformedURLException e) {
System.err.println("url construction error.");
isConnected = false;
e.printStackTrace();
}
try {
con = url.openConnection();
} catch (
IOException e) {
// TODO Auto-generated catch block
System.err.println("url connection error.");
isConnected = false;
e.printStackTrace();
}
try {
// 设置请求的路径
con.setConnectTimeout(5 * 1000);
// 输入流
is = con.getInputStream();
} catch (
SocketTimeoutException se) {
System.err.println("connect timed out.");
isConnected = false;
se.printStackTrace();
}catch (IOException e) {
System.err.println("input stream construction error.");
isConnected = false;
e.printStackTrace();
}
return isConnected;
}
public int download(String fileName) throws IOException {
File sf;
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
int downloadedSize = 0;
// 输出的文件流
sf = new File(fileName);
try {
sf.createNewFile();
} catch (IOException e) {
System.err.println("file creation error.");
e.printStackTrace();
sf.delete();
}
/*
* if(!sf.exists()){ sf.mkdirs(); }
*/
try {
os = new FileOutputStream(sf);
} catch (
FileNotFoundException e) {
System.err.println("file output stream error.");
e.printStackTrace();
sf.delete();
}
// 开始读取
//System.out.println("downloading" + fileName);
try{
while ((len = is.read(bs)) != -1) {
downloadedSize += 1024;
os.write(bs, 0, len);
}
}catch(IOException e){
e.printStackTrace();
sf.delete();
}
// 完毕,关闭所有链接
os.close();
//System.out.println("downloaded" + fileName);
is.close();
return downloadedSize;
}
------解决方案--------------------楼主,我试了你的代码,我可以正常抓图。
能否把你调用这两个方法的代码也贴出来?