Warm tip: This article is reproduced from stackoverflow.com, please click
directory java java-8 spring-boot

How to get the full system path of a directory (not file) in Spring boot with Java 8

发布于 2020-04-05 23:33:58

I am coding in Spring Boot 1.5 with Java 8 I have a directory on this path :

  C:\Users\me\IdeaProjects\MyApp\server\src\main\resources\static\documents\1\folder_a23

I don't know how i can get with a Java function this path as a String/File/Path/Stream. Is there a way to get this path as result of a search of "/folder_a23" ? Thank you very much for every answer!

Questioner
Joe Dashes
Viewed
54
630k 2020-04-02 04:25

The File Object handles everything you can do with a File on the File system. Even though the name does not properly suggest it, a File object is an abstract representation of file OR directory pathnames.

Have a look at #getAbsolutePath()

File file = new File(".....");
String absolutePath = file.getAbsolutePath();

This giles you the absolut path of the File.

If the String you used to create the File object points to a directory, you can get the content of this directory with .listFiles();

This allows you to loop through the content of a directory and perform the checks you need.

file = new File("c:/test");
File[] paths = f.listFiles();
for(File path: paths) {
    // perform your checks here
}

This function is not recursive by nature. If you want to descend into sub directories, you will need to code that on your own.

However, this assumes that you are indeed working with files. If you bundle your programm as an .jar (or .war) file and run it from there, their woun't be a file on the file system as .jar are zipped java archives.