baeldung-articles : BAEL-6607 (#16240)

Get a Path to a Resource in a Java JAR File.
This commit is contained in:
DiegoMarti2 2024-03-28 06:43:38 +02:00 committed by GitHub
parent f6a766d8ef
commit d1e36a0b4e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 32 additions and 0 deletions

View File

@ -0,0 +1,32 @@
package com.baeldung.getpathtoresource;
import org.junit.Test;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import static org.junit.Assert.assertNotNull;
public class GetPathToResourceUnitTest {
@Test
public void givenFile_whenClassUsed_thenGetResourcePath() {
URL resourceUrl = GetPathToResourceUnitTest.class.getResource("/sampleText1.txt");
assertNotNull(resourceUrl);
}
@Test
public void givenFile_whenClassLoaderUsed_thenGetResourcePath() {
URL resourceUrl = GetPathToResourceUnitTest.class.getClassLoader().getResource("sampleText1.txt");
assertNotNull(resourceUrl);
}
@Test
public void givenFile_whenPathUsed_thenGetResourcePath() throws Exception {
Path resourcePath = Paths.get(Objects.requireNonNull(GetPathToResourceUnitTest.class.getResource("/sampleText1.txt")).toURI());
assertNotNull(resourcePath);
}
}