日期:2014-05-18  浏览次数:20565 次

java下载网络文件
下面这段代码是下载一个http网络文件的代码,但有时候下载下来的图片是完整的,有时候下载下来的不完整,还有下载的ppt,pdf之类,也是打不开的。请大件们给指导一下,小弟感激不尽。
public String goDownLoad() throws IOException, URISyntaxException{ 
String urlPath ="http://www.yixue360.net/images/news/pic02.png";
URL _URL=new URL(urlPath);  
    HttpURLConnection con=(HttpURLConnection) _URL.openConnection();
    con.connect();
    InputStream fis=con.getInputStream();  
    
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();

//获取文件名 
    String trueurl=con.getURL().toString(); 
    String filename=trueurl.substring(trueurl.lastIndexOf('/')+1); 
this.getResponse().reset();
this.getResponse().setHeader("Content-Type", "application/octet-stream");
this.getResponse().addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes(), "UTF-8"));
this.getResponse().addHeader("Content-Length", "" + con.getContentLength()+10024);
SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
this.getResponse().addHeader("Date", formate.format(new Date()));
OutputStream toClient = this.getResponse().getOutputStream();
toClient.write(buffer);
toClient.flush();
toClient.close();
return null;

}
java下载 下载网络文件 下载 下载http文件

------解决方案--------------------
文件大小是不是超过了你设的Content-Length
------解决方案--------------------
用缓冲流缓冲一下。
要不容易出错。
InputStream is = URLHelper.getInputStreamByUrl("http://upload.newhua.com/6/73/1291012043416.jpg");
IOHelper.fromIputStreamToFile(is, "D:\\PP.jpg");


public static boolean fromIputStreamToFile(InputStream is,
String outfilepath) {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;

try {
// 新建文件输入流并对它进行缓冲
inBuff = new BufferedInputStream(is);

// 新建文件输出流并对它进行缓冲
outBuff = new BufferedOutputStream(
new FileOutputStream(outfilepath));

// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
} catch (Exception e) {
return false;
} finally {
try {
// 关闭流
if (inBuff != null)

inBuff.close();
if (outBuff != null)
outBuff.close();
} catch (IOExc