0

I wrote the below code inorder to write an xml output to a file in my Tomcat Server. When I ran the code I get the below error. May I know what is wrong in my code. Thanks in advance. It is supposed to create a directory with name test and then the file test.xml in the path I specified in my server. But, it is not doing doing that and instead it is looking for that path in my local machine

java.io.FileNotFounException: C:\test\test.xml The system cannot find the path specified

   // write the content into xml file
                 TransformerFactory transformerFactory = TransformerFactory.newInstance();
                 Transformer transformer = transformerFactory.newTransformer();
                 DOMSource source = new DOMSource(doc);

                 StreamResult result = new StreamResult(new File("/test/test.xml"));
                 transformer.transform(source, result);

                 // Output to console for testing
                 StreamResult consoleResult = new StreamResult(System.out);
                 transformer.transform(source, consoleResult);
James
  • 337
  • 4
  • 12
  • Do you have a /tmp directory at the root of your c drive? – Robert Moskal Oct 09 '17 at 18:18
  • No. I wanted it to write to my Tomcat folder which has a tmp directory – James Oct 09 '17 at 18:20
  • Possible duplicate of [Best practice to save temp files on tomcat?](https://stackoverflow.com/questions/23775620/best-practice-to-save-temp-files-on-tomcat) That should tell you everything you need to know. – Robert Moskal Oct 09 '17 at 18:22
  • 2
    Do not assume the presence of any directories. Use [File.createTempFile](https://docs.oracle.com/javase/9/docs/api/java/io/File.html#createTempFile-java.lang.String-java.lang.String-) instead. For example, `File.createTempFile("test", ".xml")`. – VGR Oct 09 '17 at 18:29

1 Answers1

1

By default Tomcat set value of java.io.tmpdir system property to its tmp directory. So the following piece of code should create a File object pointing to a file in Tomcat tmp:

String tempDir = System.getProperty("java.io.tmpdir");
File outputFile = new File(tempDir, "test.xml");
Aleh Maksimovich
  • 2,622
  • 8
  • 19
  • If I want to save it to create some other directory in Tomcat and then save the file in that directory, then what change should I make – James Oct 09 '17 at 18:32
  • You can calculate file location relative to your application folder in `webapps`: https://stackoverflow.com/questions/3632608/tomcat-actual-path-for-new-file-creation – Aleh Maksimovich Oct 09 '17 at 18:37
  • While I do not recomment doing this. Tomcat can be started with engine in CATALINA_BASE and runtime configuration and files in CATALINA_HOME. So the details may vary. Also any solution with permanent local file storage is not portable (e.g. when you have several Tomcat instances load balanced) – Aleh Maksimovich Oct 09 '17 at 18:42