I/O操作的问题,文件下载,急!!!!!!!!!!!!
小第有这样一个问题要请教大家。
现在我要从服务器上,写一个流,把数据读到用户的本地以excel形式显示出来。
我用sql查出了数据,写在一个Stringbuffer里面了。
现在想生成一个CSV文件,现在问题是,生成CSV文件,然后怎么才能在客户端下载,这块怎么写?是用FileOutputStream还是用什么别的来做这个操作呢?
------解决方案--------------------写一个servlet,像客户端直接response出数据,代码示例如下:
public int downFile(HttpServletResponse response, String filePathName) {
String saveUploadFilePath= "d: ";
if (filePathName.indexOf( "/ ") != 1 && filePathName.indexOf( "\\ ") != 1) {
filePathName = "/ " + filePathName;
}
java.io.File downfile = new java.io.File(fileName);
InputStream is = null;
try {
if (downfile.exists()) {
is = new FileInputStream(downfile);
}
else {
throw new
IOException( "文件不存在1! ");
}
}
catch (IOException ie) {
System.out.println( "文件不存在2! " + saveUploadFilePath + ie.getMessage());
return -100;
}
long fileLeng = 0;
try {
fileLeng = is.available();
}
catch (IOException ex) {
System.out.println( "获得文件长度失败! " + ex.getMessage());
return 1;
}
if (fileLeng > = 0) {
// 向客户端发出附件输出流
String filename = filePathName.substring(filePathName.lastIndexOf( "/ ") + 1,filePathName.length());
//String filename= "maillist.txt ";
response.setContentType( "application/x-msdownload ");
try {
response.setHeader( "Content-Disposition ", "attachment;filename= " + "maillist.txt ");
OutputStream os = response.getOutputStream();
int byteSum = 0;
int bytesRead = 0;
byte[] buffer = new byte[10 * 1024];
while ( (bytesRead = is.read(buffer)) != -1) {
byteSum += bytesRead;
os.write(buffer, 0, bytesRead);
}
is.close();
is = null;
}
catch (Exception ex) {
System.out.println( "向客户端发出附件输出流出错! " + ex.getMessage());
return 1;
}
}
return 0;
}
------解决方案--------------------晕死,
设置contentType为 "application/octet-stream ";
------解决方案--------------------就设置一下contentType就行了,