קבלת ספריית העבודה הנוכחית ב-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 + "\"" );
}
}
תְפוּקָה
Current Directory = "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();
}
}
תְפוּקָה
Current Directory = "C:\Users\DELL\eclipse-workspace\JavaProjects"
GO TO FULL VERSION