การรับไดเร็กทอรีการทำงานปัจจุบันใน Java หมายถึงการรับพาธของไดเร็กทอรี (โฟลเดอร์) จากตำแหน่งที่โปรแกรมของคุณเปิดใช้ โดยปกตินั่นหมายถึงการรับเส้นทางจากโฟลเดอร์รูทไปยังโฟลเดอร์ที่วางไฟล์โปรแกรมไว้ นี่เป็นปัญหาทั่วไปในแต่ละวันและมีหลายวิธีที่จะทำได้ใน Java อย่างไรก็ตาม เราจะเริ่มด้วยวิธีพื้นฐานที่สุดโดยใช้วิธีการในตัวของระบบ
การใช้ System.getProperty(); วิธี
public class DriverClass {
public static void main(String[] args) {
String userDirectoryPath = System.getProperty("user.dir");
System.out.println("Current Directory = \"" + userDirectoryPath + "\"" );
}
}
เอาต์พุต
ไดเรกทอรีปัจจุบัน = "C:\Users\DELL\eclipse-workspace\JavaProjects"
คำอธิบาย
ข้อมูลโค้ดด้านบนใช้เมธอด “ getProperty() ” ที่จัดทำโดย “ System ” พร้อมพารามิเตอร์มาตรฐาน “ user.dir ” มันดึงเส้นทางของไดเร็กทอรีที่มีโปรเจ็กต์ Java ของคุณ เรียกใช้ด้วยตัวคุณเองและคุณจะเห็นว่าพิมพ์ออกมาในผลลัพธ์การใช้ java.nio.file.FileSystems
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class DriverClass1 {
// Print Current Working Directory using File Systems
static void printCurrentWorkingDirectoryUsingFileSystems() {
Path currentDirectoryPath = FileSystems.getDefault().getPath("");
String currentDirectoryName = currentDirectoryPath.toAbsolutePath().toString();
System.out.println("Current Directory = \"" + currentDirectoryName + "\"");
}
public static void main(String[] args) {
printCurrentWorkingDirectoryUsingFileSystems();
}
}
เอาต์พุต
ไดเรกทอรีปัจจุบัน = "C:\Users\DELL\eclipse-workspace\JavaProjects"
GO TO FULL VERSION