简体   繁体   中英

Java file path issue

I work on a Java project with an old Framework EchoStudio3 with a Tomcat Server. I try to download a generated csv file, but i get a strange file instead.

Here is my code:

String dir = System.getProperty("user.dir");
File filename = new File(dir, "reports.csv");
FileWriter fw = new FileWriter(filename);

fw.append("User");name
fw.append(',');
fw.append("Count");
fw.append('\n');
fw.append("Bob");
fw.append(',');
fw.append("20");
fw.append('\n');
fw.append("John");
fw.append(',');
fw.append("5");
fw.append('\n');
fw.append("Mike");
fw.append(',');
fw.append("2");
fw.append('\n');
fw.append("Total");
fw.append(',');
fw.append("27");
fw.append('\n');

try {
    fw.flush();
    fw.close();
    URL url = new URL("file:///" + dir);
    FileURLConnection urlConn = (FileURLConnection) url.openConnection();
    String contentType = "text/csv";
    ApplicationInstance.getActive().enqueueCommand(new DownloadCommand(
              new FileDownload(contentType,"inline", 
              filename.getAbsolutePath(), 
              urlConn.getInputStream())));

} catch (Exception e) {
    System.out.println("Error while flushing/closing fileWriter !!!");
    e.printStackTrace();
}

I Have a Tomcat server on a local Windows environment where I test my code, but the deployed environment will be a linux environment, I don't know if this will cause another issue, but I think you should now. The download file from the code above, is named "C-Program FilesApache Software Foundationapache-tomcat-7.0.64binreports.csv", and has in it a list of tomcat files(bootstrap.jar, catalina.bat, ...) and that's really strange because the generated file exists in the bin directory, but it's not this one who's downloaded...

Is the issue comes from the file path?

Thank you for your help, the correct code is this:

URL url = new URL("file:///" + dir + "/reports.csv");
FileURLConnection urlConn = (FileURLConnection) url.openConnection();
String contentType = "text/csv";
ApplicationInstance.getActive().enqueueCommand(new DownloadCommand(
    new FileDownload(contentType,"inline", 
                     filename.toString(), 
                     urlConn.getInputStream())));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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