[英]how to get full path of the current file including the src file in java
我有一個文件dateTesting.java。 路徑的目錄如下:D:\\ workspace \\ Project1 \\ src \\ dateTesting.java。 我希望此文件的完整路徑本身為“ D:\\ workspace \\ Project1 \\ src”,但是當我使用以下任何代碼時,我只會得到“ D:\\ workspace \\ Project1”。 src部分不來了。
System.out.println(System.getProperty("user.dir"));
File dir2 = new File(".");
System.out.println(dir2.getCanonicalPath().toString());
System.out.println(dir2.getAbsolutePath());
如何獲得完整路徑為“ D:\\ workspace \\ Project1 \\ src”? 我正在使用Eclipse IDE 3.5
謝謝
dateTesting.java
是Java源文件,編譯為字節碼后不可用。 它所在的源目錄也不可用。
dir2
是在其中執行.class
文件的目錄的File
。它似乎是D:\\workspace\\Project1
但您不能依靠它。
您的dir2指向工作目錄( new File(".")
)。 您無法通過這種方式獲取源的位置。 您的文件可以放在包中(例如your.company.date.dateTesting
)。 您應該只手動將“ src”連接到當前工作目錄,然后用File.pathSeparator
替換文件包點( .
)。 這樣,您將構建文件的完整路徑。
String fullFilePath = "H:\\Shared\\Testing\\abcd.bmp";
File file = new File(fullFilePath);
String filePath = file.getAbsolutePath().substring(0,fullFilePath.lastIndexOf(File.separator));
System.out.println(filePath);
輸出:H:\\ Shared \\ Testing
如果您這樣做是為了嘗試從類路徑中讀取文件,請查看以下答案: 如何從Java中的類路徑中真正讀取文本文件
基本上你可以做到
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
否則,如果您有其他要求,一種選擇是在應用程序啟動時以JVM arg的身份通過src目錄,然后將其讀回。
/** The actual file running */
public static final File JAR_FILE = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
/** The path to the main folder where the file .jar is run */
public static final String BASE_DIRECTORY = (JAR_FILE != null ? JAR_FILE.getAbsolutePath().replace(JAR_FILE.getName(), "") : "notFound");
這將在正常的Java執行和jar執行中為您工作。 這是我在項目中使用的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.