這幾天因爲項目需要,寫一個通過文件流下載文件的東西。整個過程需要一個後臺服務器和一個GUI的程序,GUI做下載操作。
URLConnection conn = url.openConnection();
int contentLength = conn.getContentLength();
System.out.println("########## length = " + contentLength);
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(saveFile);
byte[] buffer = new byte[10240];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.print(bytesum);
fs.write(buffer, 0, byteread);
long downloadPercent = bytesum * 100 / contentLength ;
MainClass.dwProgressBar.setValue((int)downloadPercent); //進度值
System.out.println(" ; percents: " + downloadPercent);
}
fs.close();
GUI端的下載便做好了。
String filePath = getServletContext().getRealPath(File.separator) + "mptd" + File.separator + path
+ File.separator + sName + File.separator;
System.out.println(filePath);
String fileName = new File(filePath).list()[0];
File file = new File(filePath + fileName);
System.out.println(file.getAbsolutePath());
System.out.println(file.isFile());
FileInputStream fis = new FileInputStream(file);
PrintWriter out = response.getWriter();
int b = 0;
while ((b = fis.read()) != -1) {
out.write(b);
}
response.setHeader("Content-Disposition","attachment;filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
response.setHeader("Content-Length","" + file.length());
fis.close();
out.close();
服務器端的下載代碼也就這樣。
好了,我們可以愉快的玩耍了
...
咦,怎麼回事兒?下載不動啊,GUI客戶端下載,文件長度爲-1,下載進度一直都爲負數。
折騰半天,原來問題在服務器端的這兩句話:
response.setHeader("Content-Disposition","attachment;filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
response.setHeader("Content-Length","" + file.length());
這兩句話一定要放在文件讀寫之前,放在讀寫之後就不起作用了。所以改成下面這樣就好了:
String filePath = getServletContext().getRealPath(File.separator) + "mptd" + File.separator + path
+ File.separator + sName + File.separator;
System.out.println(filePath);
String fileName = new File(filePath).list()[0];
File file = new File(filePath + fileName);
response.setHeader("Content-Disposition","attachment;filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
response.setHeader("Content-Length","" + file.length());
System.out.println(file.getAbsolutePath());
System.out.println(file.isFile());
FileInputStream fis = new FileInputStream(file);
PrintWriter out = response.getWriter();
int b = 0;
while ((b = fis.read()) != -1) {
out.write(b);
}
fis.close();
out.close();
好了,現在真的可以愉快的玩耍了。