Skip to content

Instantly share code, notes, and snippets.

@hrchu
Created October 22, 2022 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrchu/b4a10b776c28a718ff2fb81d8ee69b62 to your computer and use it in GitHub Desktop.
Save hrchu/b4a10b776c28a718ff2fb81d8ee69b62 to your computer and use it in GitHub Desktop.
Relative path handling in Java
package org.example;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
public class PlayPath {
public static void main(String[] args) throws URISyntaxException {
// base path of relative path is current directory
String basePath = new File("").getAbsolutePath();
System.out.println(basePath);
// access file
Path p = Path.of("pos1.jpg"); // pos1.jpg
System.out.println(Files.exists(p));
// access resource
ClassLoader classLoader = new PlayPath().getClass().getClassLoader();
URI resource = classLoader.getResource("pos2.jpg").toURI(); // src/main/resources/pos2.jpg
System.out.println(Files.exists(Path.of(resource)));
// TODO:Spring resource
// https://www.baeldung.com/spring-classpath-file-access
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment