0

Server: tomcat.

I created a Servlet to call JAVA program to process CSV file.

The code new ToJSON().main(files) will process the csv files to json.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String [] files = request.getParameter("files").split(",");
    System.out.println(String.join(",", files));
    new ToJSON().main(files);
    ////call the java program to convert CSV files to json then sent the file name or the contain back.
    response.getWriter().append("data.json");
}

SEVERE: Servlet.service() for servlet [charting.servlet.ChartingServlet] in context with path [/Charting] threw exception
java.io.FileNotFoundException: BankFileLine.csv (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at format.LoadCSVFile.iterable(LoadCSVFile.java:60)
at format.LoadCSVFile.getMaxLength(LoadCSVFile.java:44)
at format.LoadCSVFile.<init>(LoadCSVFile.java:26)
at toJSON.ToJSON.main(ToJSON.java:26)

But I kept getting filenotfoundexception. I tried to put the files into WebContent and src. none of them worked. I tried to adding the path:localhost:8080/ChartingServlet/filename, still did not work.

Here is the directories Here is the directories of the project files

My question is where I should put the files?

Kreedz Zhen
  • 380
  • 2
  • 12

1 Answers1

-1

The current directory while running on the server is not anything you should count on, and nothing you've shown takes that into consideration.

1) If the csv files are not to be served to the client, you don't actually care where the file is, you only care about reading the correct contents. For this case you can put them under your src folder and then get an InputStream to their contents using #getResourceAsStream() from your servlet class. This works the same way as it would in a normal Java application, and won't break if you want to package your web-app as a WAR file.

2) If the client should be able to read the original .csv, you'll want to get the ServletContext from your request object, and then build your filesystem absolute path using ServletContext#getRealPath(), passing in paths relative to your WebContent folder so you know the absolute location of your files, which you can then read as normal. This method doesn't tend to survive packaging your app as a WAR file. You could try ServletContext#getResourceAsStream() in that scenario, but I don't have first-hand experience with that, so I'm not sure it works.

nitind
  • 19,089
  • 4
  • 34
  • 43