简体   繁体   中英

How do I get the File API to look at my classpath?

I am reading an ascii file in in my eclipse project.

The default output folder is set as

my_proj/classes

It is on my source path and when I build it goes into my classes directory. All ok. However, when I try to get a handle to it in my code by doing

File myFile = new File("myFile.txt")

it won't work because that API looks at my project root. Not at my classes dir.

When I do:

System.out.println("Current path is = " + new File(".").getAbsolutePath ()); 

The project roo comes back not my classes dir.

So hence I can't get a handle to my File.

I would like to just have the File on the classpath and for the code to pick it up

Any tips?

You can use getClass().getClassLoader().getResource("Your_File")

and then use something like

 File file=new File(url.toURI());

Edit: as pointed out by Sotirios Delimanolis and jb-nizet , if "Your_File" is not a file on the file system but is bundled within a jar, in that case you will have to work with the inputstream, getClass().getClassLoader().getResourceAsStream("Your_File")

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