加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala读取项目中的文件

发布时间:2020-12-16 09:36:39 所属栏目:安全 来源:网络整理
导读:一、获取jar包的位置 1.使用类路径 String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 返回值都是/xxx/xxx.jar这种形式。如果路径包含Unicode字符,还需要将路径转码 path = java.net.URLDecoder.decode(path,

一、获取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=xxxxxxx;xxxxxx;这里获得的就是这个分号。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读