java如何做文件下载?
我想将服务器上的文件生成到本地上,该怎么做?
------解决方案--------------------用sevlet输出就可以了
看下以前的贴子
http://community.csdn.net/Expert/topic/5604/5604422.xml?temp=.8975641
------解决方案--------------------可以把文件通过流,写到writeprint对象里面,writprint对象可以通过response.getWrite()方法得到。
------解决方案--------------------在你的jdk(1.4.2)的Demo包包下面就有一个文件下载的例子,名字好像是CartBar,自己有空研究研究
------解决方案--------------------http://schmidt.devlib.org/java/file-download.html
import java.io.*;
import java.net.*;
/*
* Command line program to download data from URLs and save
* it to local files. Run like this:
* java FileDownload http://schmidt.devlib.org/java/file-download.html
* @author Marco Schmidt
*/
public class FileDownload {
public static void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
URL url = new URL(address);
out = new BufferedOutputStream(
new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
}
System.out.println(localFileName + "\t " + numWritten);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (
IOException ioe) {
}
}
}
public static void download(String address) {
int lastSlashIndex = address.lastIndexOf( '/ ');
if (lastSlashIndex > = 0 &&
lastSlashIndex < address.length() - 1) {
download(address, address.substring(lastSlashIndex + 1));
} else {
System.err.println( "Could not figure out local file name for " +
address);
}
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
download(args[i]);
}
}
}
------解决方案--------------------String filename = "C:\\123.xls ";
response.setContentType( "text/x-msdownload ");
response.addHeader( "Content-Disposition ",
"attachment; filename=\ " " + new String(filename.getBytes(), "ISO-8859-1 ") + "\ " ");
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(filename);
byte[] b = new byte[1024];
int i = 0;
while ( (i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
------解决方案--------------------up~~输入输出流是我一直困惑的问题~~希望多和大家探讨探讨
------解决方案--------------------先读出
InputStream is = FileInputStream();
后写到本地
outputStream os = FileOutputStream();