如何将字符串保存到csv文件?

yinleiyoung 2008-03-25 04:24:38
现在Action中得到一个Service端返回的字符串 String test = “xxxxxxxxxxxxxx”, 现在要将它保存到一个CSV文件,文件名默认为test.csv,请问怎么实现?
谢谢!
...全文
965 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangzi315 2008-03-26
  • 打赏
  • 举报
回复
解决乱码可以如下:
<%
java.io.BufferedInputStream bis=null;
java.io.BufferedOutputStream bos=null;
try{
String filename=request.getParameter("filename");
filename=new String(filename.getBytes("iso8859-1"),"gb2312");
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition","attachment; filename="+new String(filename.getBytes("gb2312"),"iso8859-1"));
bis =new java.io.BufferedInputStream(new java.io.FileInputStream(config.getServletContext().getRealPath("files/" + filename)));
bos=new java.io.BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
if (bis != null)bis.close();
if (bos != null)bos.close();
}
%>
注意,关键就是setHeader里的filename需要重新编码,格式是ISO-8859-1就OK了
yinleiyoung 2008-03-26
  • 打赏
  • 举报
回复
to yangzi315,
我这里只有一个字符串String, 我不需要,也没有文件可以读取
robin_ares 2008-03-26
  • 打赏
  • 举报
回复
response.setContentType("application/text;charset="UTF-8");
response.setHeader("Content-disposition", "attachment;filename=11.csv");
DataOutputStream out;
try{
out = new DataOutputStream(response.getOutputStream());
out.write("AAAA".getBytes("UTF-8"));
out.close();
}......
yinleiyoung 2008-03-25
  • 打赏
  • 举报
回复
谢谢!
我现在碰到了乱码问题,我用的是UTF-8格式,英文操作系统,当有中文下载到CSV文件的时候,出现乱码
老紫竹 2008-03-25
  • 打赏
  • 举报
回复
out.clearBuffer();
String filename="test.csv";
response.addHeader("Content-Disposition", new String(("attachment; filename=" + filename).getBytes("GBK"), "ISO-8859-1"));
response.setContentType("application/vnd.ms-excel");
// 后面输出你的字符串吧
yinleiyoung 2008-03-25
  • 打赏
  • 举报
回复
对了,我还需要跳出 “下载” “保存” 对话框

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧