Get Current Directory Using Java
This commit is contained in:
parent
2e522b3ab8
commit
c9599313c8
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.core.pwd;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public final class CurrentDirectoryFetcher {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.printf("Current Directory Using Java System API: %s%n", currentDirectoryUsingSystemProperties());
|
||||
|
||||
System.out.printf("Current Directory Using Java IO File API: %s%n", currentDirectoryUsingFile());
|
||||
|
||||
System.out.printf("Current Directory Using Java NIO FileSystems API: %s%n", currentDirectoryUsingFileSystems());
|
||||
|
||||
System.out.printf("Current Directory Using Java NIO Paths API: %s%n", currentDirectoryUsingPaths());
|
||||
}
|
||||
|
||||
public static String currentDirectoryUsingSystemProperties() {
|
||||
return System.getProperty("user.dir");
|
||||
}
|
||||
|
||||
public static String currentDirectoryUsingPaths() {
|
||||
return Paths.get("")
|
||||
.toAbsolutePath()
|
||||
.toString();
|
||||
}
|
||||
|
||||
public static String currentDirectoryUsingFileSystems() {
|
||||
return FileSystems.getDefault()
|
||||
.getPath("")
|
||||
.toAbsolutePath()
|
||||
.toString();
|
||||
}
|
||||
|
||||
public static String currentDirectoryUsingFile() {
|
||||
return new File("").getAbsolutePath();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.core.pwd;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CurrentDirectoryFetcherTest {
|
||||
|
||||
private static final String CURRENT_DIR = "core-java-os";
|
||||
|
||||
@Test
|
||||
public void whenUsingSystemProperties_thenReturnCurrentDirectory() {
|
||||
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingSystemProperties()
|
||||
.endsWith(CURRENT_DIR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJavaNioPaths_thenReturnCurrentDirectory() {
|
||||
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingPaths()
|
||||
.endsWith(CURRENT_DIR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() {
|
||||
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFileSystems()
|
||||
.endsWith(CURRENT_DIR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJavaIoFile_thenReturnCurrentDirectory() {
|
||||
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFile()
|
||||
.endsWith(CURRENT_DIR));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue