简体   繁体   中英

Read a file in Java from classpath, absolute path, relative path that includes “../..” path

Before marking this a duplicate, please read! I have searched SO and other repositories for this solution.

The below Spring API works if filepath is absolute path file://some/path or if its a path in the Classpath /some/class/path . However, this API fails to handle relative path that includes "../".

File f = new DefaultResourceLoader().getResource(filepath).getfile();

I have been working around this issue by falling back to the below if the above fails -

File f = new File(filepath)

Is there a way to avoid this fallback logic and use a file API that works irrespective of file path?

The other solution I came across that suggests using getClass().getResource() also requires fallback API to deal with absolute/relative paths.

File absolute = new File(filepath).getAbsoluteFile();

And use further what works well:

The below Spring API works if filepath is absolute path file://some/path

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