scala/java讀取項目中的文件


一、獲取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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM