您的位置:首页 > 编程语言 > Java开发

struts文件下载---自主写入下载内容

2013-11-30 21:52 330 查看
本文主要是为了说明如何在下载内容的时候自己写入内容。例如从list中获取内容然后写入下载文件中。

首先来分析下场景。查询出学生信息,需要将查询出来的信息进行下载,并进行保存(可自定义文件名和类型)。

下面下贴出struts.xml的代码:

<struts>
<constant name="struts.i18n.encoding" value="gb2312"></constant>
<package name="struts2" extends="struts-default" namespace="/upLoadFile">
    <!-- 简单文件下载 -->
<action name="download" class="com.nighthary.action.FileDownloadAction">
<result name="success" type="stream">
<param name="contentType">text/plain</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="downLoad.txt"</param>
<param name="bufferSize">4096</param>
</result>
</action>
</package>
</struts>


  

然后是action的内容:

/**
* struts实现的文件下载,用户可以自己写入内容以及保存的文件名
* @author NightHary
*
*/
public class FileDownloadAction implements Action {
public List<Student> studentList = new ArrayList<Student>();
public InputStream getInputStream() throws Exception {
Map session = ActionContext.getContext().getSession();
studentList = (List<Student>)session.get("resultList");
String a = "";
for(int i=0;i<studentList.size();i++){
a += studentList.get(i).getId()
+"\t"+studentList.get(i).getName()
+"\t"+studentList.get(i).getAge()+"\r\n";
}
return new ByteArrayInputStream(a.getBytes());
}
public String execute() throws Exception {
return SUCCESS;
}
}


这里实现的主要原理就是,将list中的数据保存到字符串中,开始使用\n来换行,没有实现,后面经过度娘的帮助,使用\r\n解决了问题。

各系统应当是:
\r Mac
[b]\n Unix/Linux

\r\n Windows[/b]

现在解决了自定义下载内容的实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: