標籤:net 資源 ast 技術 csharp fir substring 斜杠 .net
一、擷取jar包的位置1.使用類路徑
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
傳回值都是/xxx/xxx.jar這種形式。如果路徑包含Unicode字元,還需要將路徑轉碼
path = java.net.URLDecoder.decode(path, "UTF-8");
2.利用了java運行時的系統屬性來得到jar檔案位置,也是/xxx/xxx.jar這種形式
String path = System.getProperty("java.class.path"); int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1; int lastIndex = path.lastIndexOf(File.separator) + 1; path = path.substring(firstIndex, lastIndex);
path.separator在Windows系統下得到;(分號),在Linux下得到:(冒號)。也就是環境變數中常用來分割路徑的兩個符號,比如在Windows下我們經常設定環境變數PATH=xxxx\xxx;xxx\xxx;這裡獲得的就是這個分號。
File.separator則是/(斜杠)與\(反斜線),Windows下是\(反斜線),Linux下是/(斜杠)。
二、讀取jar包中的檔案1.先得到該檔案的路徑,再載入該檔案資源
java.net.URL fileURL = this.getClass().getResource("/UI/image/background.jpg"); javax.swing.Image backGround = new ImageIcon(fileURL).getImage();2.直接載入該對象
InputStream in = this.getClass().getResourceAsStream("/UI/image/background.txt");三、jar包程式的運行 1.java
java -classpath F:/TestHello.jar Test2或者java -cp F:/TestHello.jar Test2
2.scala
scala -classpath F:/TestHello.jar Test2
scala/java讀取項目中的檔案