May 8, 2012

JAVA - Reading file relatively

This will all getting the base path of you application to know how/where to read the file

Eclipse

Java Application


* File function
File fXmlFile = new File("test.xml");
The will look on the PROJECT_DIR path.
/YOUR/PROJECT_DIR/test.xml
* FileInputStream
FileInputStream is = new FileInputStream("test.cfg.xml");

The will look on the ECLIPSE path.
/YOUR/ECLIPSE_DIR/test.cfg.xml

*
Loader context
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
classLoader.getResource(".").getPath()
This will return: PROJECT_DIRt/build/classes/

Web Application(Running in Tomcat)


*
Loader context
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
classLoader.getResource(".").getPath()
This will return the path TOMCAT_DIR/lib/

* File function
File fXmlFile = new File("test.xml");
The will look on the ECLIPSE_DIR path.
/YOUR/ECLIPSE_DIR/test.xml

Deployed


* Java Application

* Web Application(Running in Tomcat)
* Loader context
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
classLoader.getResource(".").getPath()
This will return the path TOMCAT_DIR/lib/

* File function
File fXmlFile = new File("test.xml");
The will look on the
TOMCAT_DIR path.
/TOMCAT_DIR/test.xml

No comments: