title: Tomcat server absolute file access in war webapp
body: <p>I have a Spring webapp whose <code>.war</code> file has been uploaded to a Tomcat server. Most of the basic functions are working as intended - page views and form submission. </p>
  
  <p>My problem now is that my webapp needs to read and write files and I am clueless as to how I can achieve this (the file I/O returns <code>java.lang.NullPointerException</code>). </p>
  
  <p>I used the following <a href="https://stackoverflow.com/a/9346892/1685185">code to get the absolute path of a given file</a> suggested by <a href="https://stackoverflow.com/users/460856/titi-wangsa-bin-damhore">Titi Wangsa Bin Damhore</a> to know the path relative to the server:</p>
  
  <pre><code>HttpSession session = request.getSession();
  ServletContext sc = session.getServletContext();
  String file = sc.getRealPath("src/test.arff");
  logger.info("File path: " + file);
  </code></pre>
  
  <p>Here is the output path:</p>
  
  <pre><code>/home/username/tomcat/webapps/appname/src/test.arff
  </code></pre>
  
  <p>But when I checked the file directory via <a href="http://winscp.net/eng/index.php" rel="nofollow noreferrer">WinSCP</a>, the file's actual path is:</p>
  
  <pre><code>/home/username/tomcat/webapps/appname/WEB-INF/classes/test.arff
  </code></pre>
  
  <p><strong>Here are my questions</strong>:</p>
  
  <ol>
  <li>How do I transform these paths into something like <code>C:/Users/Workspace/appname/src/test.arff</code> (the original path in my local machine that works perfectly)? It's servers are <code>Apache Tomcat 6.0.35</code> and <code>Apache Tomcat 6.0.35</code>.</li>
  <li>Why is the code returning a different path as opposed to the actual path? </li>
  <li>If file I/O is not applicable, what alternatives can I use?</li>
  </ol>
  
  <p><strong>PS</strong> I just need to access two files (&lt; 1MB each) so I don't think I may need to use a database to contain them as suggested by <a href="https://stackoverflow.com/users/1271255/minus">minus</a> in <a href="https://stackoverflow.com/a/13626916/1685185">this thread</a>.</p>
  
  <p><strong>File I/O</strong></p>
  
  <p>Below is the code I use for accessing the file I need. </p>
  
  <pre><code>BufferedWriter writer;
      try {
          URI uri = new URI("/test.arff");
          writer = new BufferedWriter(new FileWriter(
              calcModelService.getAbsolutePath() + uri));
  
          writer.write(data.toString());
          writer.flush();
          writer.close();
      } catch (IOException e) {
          e.printStackTrace();
      } catch (URISyntaxException e) {
          e.printStackTrace();
      }
  </code></pre>