Created
October 22, 2022 14:57
-
-
Save hrchu/b4a10b776c28a718ff2fb81d8ee69b62 to your computer and use it in GitHub Desktop.
Relative path handling in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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