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

猜你喜欢

转载自www.cnblogs.com/feiyumo/p/9205007.html