简体   繁体   中英

Can't access a folder in java package

I want to read all of the files from within my package without using my entire file path. For example I can use something like this to get all of the files in a dir.

new File("/Users/me/Documents/workspace/testing/src/main/java/resources/").listFiles()

When I have a package in intellij that looks like this:

main
- java
--com.testFile
--resources

I read this: Read file from a folder inside the project directory . However I want to be able to do this without specifying the the whole path.

For example it is explained here: How to read a file (eg txt file) from another java package withouth specifying the absolute path?

I thought I could do something like

"src/main/java/resources" but every combination I try fails when plugged in to:

new File("/Users/me/Documents/workspace/testing/src/main/java/resources/").listFiles()

I could have sworn I've done this before like this? Am I making a silly mistake?

As of right now it can't locate the file. It's being run from a file in a file in java -> com.thisproject/app

For example I'm seeing:

File folder = new File("src/");
File[] listOfFiles = folder.listFiles();

have listOfFiles be null.

Solved... This was actually kind of weird. Everything I found online said to reference src/main etc... Which is my file path.

However I was able to access it through:

new file("java/resources").listFiles(); 

Which works perfectly. If I were to try any of the below combinations:

new file("/java/resources").listFiles(); 
new file("main/java/resources").listFiles(); 
new file("src/main/java/resources").listFiles(); 

They all fail.

For system info I'm using intellij, Mac OS, I'm working on a intellij created webapp. Not sure if that makes a difference.

If anyone knows why src/... doesn't work I'd love to know.

This worked for me with eclipse running on Windows OS:

System.out.println(new File("src/").listFiles().length); // printing the no. of files for checking.

So, for you it would be: "src/main/java/resources/" .

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