日期:2014-05-20  浏览次数:20682 次

jsp中将textarea的内容保存到文本文件,怎么弄
jsp中将textarea的内容保存到文本文件,我想手动指定要保持的文件路径和文件名,像另存为效果一样,怎么做,我用得是struts1

------解决方案--------------------
要实现你要的功能,代码有点多。。

告诉一下流程:
1. 页面提交textarea的内容
2. action接收内容,然后写一个方法将这些内容写入一个txt文件,存放在temp临时目录
3. 写一个文件下载的类,将2步生成的文件名下载下来。
4. 另存为效果是
//弹出下载对话框的关键代码
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename="+ filename);
这段代码弹出来的。。

给你贴一段下载的代码:
/**
* 下载服务器中的txt文件
* @param filePath
* @param filename
* @param response
* @throws Exception
*/
public static void download(File filePath, String filename, HttpServletResponse response) throws Exception{
// TODO Auto-generated method stub
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;

//File uploadFile = new File(filePath);
File uploadFile = filePath;
fis = new FileInputStream(uploadFile);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
filename = URLEncoder.encode(filename, "GBK");

//弹出下载对话框的关键代码
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename="+ filename);
int bytesRead = 0;
//都是用输入流进行先读,然后用输出流去写,用的是缓冲输入输出流
byte[] buffer = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
try{
bos.write(buffer, 0, bytesRead);
}catch(Exception e){}
}
try{bos.flush();}catch(Exception e){} 
try{bos.close();}catch(Exception e){}
try{bis.close();}catch(Exception e){}
try{fos.close();}catch(Exception e){}
try{fis.close();}catch(Exception e){}
}