简体   繁体   中英

Java: Accessing files that are in the same directory as your source file

  1. How do i access a file that is in the same directory as my source file? I have seen it done in a tutorial and it was extremely simple, but any searches I conduct on the subject are too broad. any help? ie

    doSomething("file.xml")

  2. How do I access a file relative to the source file i am working with? i haven't seen how to do this, but since it would be an acceptable solution for the first question, here it is: ie

    doSomething("src/com.package.file.xml")

I really just want a platform independent way to access files in my project. I know its probably a duplicate but please don't hate me.

Generally, you shouldn't

Files stored in the src directory (especially in Eclipse) won't be accessible at when the application is build and deployed.

Netbeans will package these files as part of your Jar when you build it, Eclipse requires you to these files stored in a separate "resources" directory within the project.

At this point, they become known as "embedded resources" and can no longer be accessed like a normal file, but instead, need to be loaded via the resources functionality available in your class.

For example.

To access the resource in com/package/file.xml , you would typically use some thing like...

getClass().getResource("/com/package/file.xml");

This will return a URL which represents the reference to the resource. If it's more confidnent, you can also gain an InputStream directly to the resource using something like...

getClass().getResourceAsStream("/com/package/file.xml");

Which will return an InputStream to the named resource...

This all of course, assumes that the resource can be found ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM