1、 得到jar加載路徑App爲jar中類名稱java
第一種:jvm
String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 若是有中文; path = java.net.URLDecoder.decode(path, "UTF-8");
第二種:.net
String path2 = PetController.class.getProtectionDomain().getCodeSource().getLocation().getFile();
第三種:(jvm實現)code
String javaPath = System.getProperty("java.class.path");
獲取分割符,好比加載了多個jar就須要分割資源
System.out.println(System.getProperty("path.separator") + "path.separator"); int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1; int lastIndex = path.lastIndexOf(File.separator) + 1; path = path.substring(firstIndex, lastIndex);
加載資源路徑下文件/UI/background.jpg是從項目根路徑開始的字符串
java.net.URL fileURL = App.class.getResource("/UI/background.jpg"); System.out.println( fileURL.getPath()); InputStream ins = fileURL.openStream();
寫到jar包外的絕對路徑get
OutputStream outs = new FileOutputStream("/Users/heliming/IdeaProjects/dm8/src/main/resources/UI/2.jpg"); byte[] bytess = new byte[2048]; //接受讀取的內容(n就表明的相關數據,只不過是數字的形式) int ns = -1; //循環取出數據 while ((ns = ins.read(bytess, 0, bytess.length)) != -1) { //轉換成字符串 //寫入相關文件 outs.write(bytess, 0, ns); }
讀取項目根路徑string
InputStream in = App.class.getResourceAsStream("/UI/background.txt"); byte[] bytes = new byte[2048]; //接受讀取的內容(n就表明的相關數據,只不過是數字的形式) int n = -1; //循環取出數據 while ((n = in.read(bytes, 0, bytes.length)) != -1) { //轉換成字符串 String str = new String(bytes, 0, n, "UTF-8"); //這裏能夠實現字節到字符串的轉換,比較實用
直接輸出it
System.out.println(str); } in.close();