Reputation: 57
I'm pretty new to Java, I've only started to code a few weeks ago, so please be patient with me :)
I want to send an XML file through an HTTP Post Request, and i'm able to simulate everything perfectly, the problem is when i dont create the XML, but actually have an XML, on the same level as my class, and i cant seem to use it, no matter what i do, what path i put in, i cant get the file to load.
example: I have a class caleld SendPostRequest.class, on the same directory i have details.xml, i'm trying to:
getClass().getResource("details.xml"); // returns null
I've tried every other combination, with the full path, or the patfrom the path i get throughSystem.getProperty("user.dir");
and nothing, it just wont load.
i'm sure i'm missing something very silly, i'm using Intellij, is there any shortcut to doing this??? for starters, i just want to load the xml into a String, just to print it out to see its working...
many thanks in advance!
Upvotes: 0
Views: 262
Reputation: 4830
Do you perhaps build with Maven? The reason I ask is because I recently had the same weird problem, I just couldn't load the .xml file, because it wasn't included in the built jar, but why? It should be....
Hmm after a bit of troubleshooting I ended up in the pom.xml
and it turns out that resources with file extension*.xml
wasn't included in the build.
<project>
...
<build>
...
<resources>
<resource>
...
<includes>
<include>**/*.xml</include>
</includes>
</resource>
After adding the file extension as in snippet above all was fine, the xml file was built in the jar and I could access the resource. Don't know if this is the case for you but this shitty little include did mess up a couple of hours for me...
Upvotes: 1
Reputation: 561
If you are running linux/unix make sure, that your java application has rights for reading that. You wrote, that you already tried loading this file via full path?
You could try to print out the current working directory like this:
public class Test
{
public static void main(final String[] args)
{
final String dir = System.getProperty("user.dir");
System.out.println("current dir = " + dir);
}
}
And then try to add the relative path to that current directory for reading in the file.
Upvotes: 0
Reputation: 1375
getClass().getResource()
loads resources not from a file system path but from the classpath. Ensure that the file is within the classpath.
Upvotes: 0