Reputation: 179
I need to know where I should place the xml file inside the Java project. I need to access the placed xml file and parse it. I have tried using resources folder but its not working out for me. Can someone suggest me a good idea on how to access the xml file which is placed within the JAVA project. I am using Eclipse IDE.
Upvotes: 1
Views: 18638
Reputation: 5496
use like below class --
this.getClass().getClassLoader().getResourceAsStream("path of file");
NOTE : this xml file structure in project
+pro
+src
+resource
-test.xml
Example:
public class ReadFile {
public void testReadFile() {
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("/Resources/tset.xml");
//praparing DOM
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
// by sending input stream as input to DOM
Document doc = docBuilder.parse(in);
}
public static void main(String[] args) {
ReadFile file = new ReadFile();
file.testReadFile();
}
}
Upvotes: 2
Reputation: 2790
You need to make sure that Eclipse includes /resources folder into the application classpath.
Open your launcher from Run Configurations
, goto Classpath
tab and if it's not there - add it.
The file can be read with this.getClass().getClassLoader().getResource*
methods.
Upvotes: 0
Reputation: 1558
resources folder is the correct folder to place your xml file. If it is not finding the file in that folder, then it may not be on classpath. So, add this folder to your project's classpath.
Go to Project -> Properties -> Java Build Path -> Source -> Add Folder
Then add the resources folder to your classpath. Thats all...You are good to go..
Upvotes: 1
Reputation: 635
You can use the structure of maven : Project/src/main/resources
I suppose it is a data xml file. If it is a config file a better way is to access it via the classpath. This is a common place where to put the resources, but you can choose your own directory. If you have problem to open the file, it is your path which is not correct. Try first to open it with a absolute path. Something like d:/workspace/Project/src/main/resources/file.xml. It will works.
Upvotes: 1