scala/java讀取項目中的檔案

來源:互聯網
上載者:User

標籤: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讀取項目中的檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.