简体   繁体   English

Java生成并下载csv文件

[英]Java generate and download csv file

I'm trying to generate and download csv file in a Java project that use an old framework called Echo Studio 3, with Tomcat. 我正在尝试在Java项目中生成和下载csv文件,该Java项目使用带有Tomcat的称为Echo Studio 3的旧框架。

here is my code: 这是我的代码:

List<Object> reportCount = this.getReport(accountId);
ArrayList<String[]> result = new ArrayList<String[]>();
for (Object list: reportCount) {
    String[] rowReport = (String[]) list;
    result.add(new String[]{String.valueOf(rowReport[0]),String.valueOf(rowReport[1])});
}

File filename = new File("report.csv");
FileWriter fw = new FileWriter(filename);
fw.append("Name");
fw.append(',');
fw.append("Count");
fw.append('\n');
for (String[] ls: result){
    fw.append(ls[0].toString());
    fw.append(',');
    fw.append(ls[1].toString());
    fw.append('\n');
}
try {
    fw.flush();
    fw.close();
} catch (Exception e) {
    System.out.println("Error while flushing/closing fileWriter !!!");
    e.printStackTrace();
}

When the code is triggered, nothing happens, and i have no error message. 当代码被触发时,什么也没有发生,并且我没有错误消息。 when i run the debug mode, the result is filled with data, and the breakpoint pass throw the flush(), and no error, and the client is not getting the generated file, did I miss something? 当我运行调试模式时,结果充满了数据,并且断点传递抛出了flush(),并且没有错误,并且客户端没有获取生成的文件,我错过了什么吗?

You're writing the file to the current working directory, which may be something you don't expect if you're running the program in a container like Tomcat. 您正在将文件写入当前的工作目录,如果您正在像Tomcat这样的容器中运行程序,则可能不希望这样做。

Given you've seen the program execute the calls, i'd test that hypothesis by changing the file path to an absolute path, to make sure that the code is actually writing correctly. 鉴于您已经看到程序执行了调用,我将通过将文件路径更改为绝对路径来测试该假设,以确保代码实际上在正确编写。 If it does, then it's just a path issue. 如果确实如此,那么这仅仅是一个路径问题。

You could also add a call to find the current working directory 1 . 您还可以添加呼叫以找到当前的工作目录1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM