Properties 配置文件以及在项目中获取资源的绝对路径

Properties 配置文件以及在项目中获取绝对路径

一、.class文件

.java文件,就是当前编写的代码文件;
.class文件,就是编译过后的文件,jvm只识别.class文件;
javac用来编译java文件生成字节码文件.class,java用来执行。

二、Properties配置文件

  1. Properties配置文件中,元素按map<String,String>存放。
  2. 呈现方式如图:在这里插入图片描述
  3. 代码展示:
 public static void main(String[] args) throws IOException {
        Properties prop = new Properties();//创建属性集对象
        FileInputStream fis = new FileInputStream("src/Pointer/Pointer.properties");
        InputStreamReader ism = new InputStreamReader(fis);
        FileOutputStream fos = new FileOutputStream("src/Pointer/Pointer.properties");
        //字节流写入,默认转换成ANCII码,使用UTF-8和GBK都可以读
        OutputStreamWriter osw = new OutputStreamWriter(fos);

        //设置属性集内容
        int age = 18;
        prop.setProperty("age2",age+"");
        prop.setProperty("name2","李四");
        prop.store(fos,"文件的注释,可以是空白字符");//load,store 字符流和字节流都可以作为参数

        prop.load(fis);//获取内容,读取之后,会在下一次的store里再次存储进去。
        String name = prop.getProperty("name2");
        System.out.println(name);

        //System.out.println("#\u6587\u4EF6\u7684\u6CE8\u91CA\uFF0C\u53EF\u4EE5\u662F\u7A7A\u767D\u5B57\u7B26");
    }

注意
1.在store之前调用load会将文件中获取的内容再次存储进文件;
2.load和store方法都支持字符流和字节流,字节流写入,默认转换成ANCII码,使用UTF-8和GBK都可以读;
3.在File/setting/File Encoding处可以修改properties文件的编码方式;
在这里插入图片描述
Transparent native-to-ascii conversion的意思是:自动转换ASCII编码。
他的工作原理是:在文件中输入文字时他会自动的转换为Unicode编码,然后在idea中发开文件时他会自动转回文字来显示。这样做是为了防止文件乱码。

在项目中获得资源的绝对路径(在out文件中,src文件已经不存在)

共有三种方式,代码如下:

public static void main(String[] args) throws IOException, URISyntaxException {
        //获取ReDemo所在路径下的资源路径,可通过toURI方法解决路径中空格被"20%"替换的问题
        String path1 = RecourseDemo.class.getResource("pr.txt").toURI().getPath();
        System.out.println(path1);
        FileReader fr = new FileReader(path1);
        BufferedReader br = new BufferedReader(fr);
        System.out.println(br.readLine());

        //利用相对路径获取项目下的资源
        String path2 = RecourseDemo.class.getResource("../Pointer.properties").getPath();
        System.out.println(path2);

        //利用类加载 getClassLoader(),URLDecoder.decode(path3,"utf-8")也可以解决空格问题
        String path3 = RecourseDemo.class.getClassLoader().getResource("Pointer/Pointer.properties").getPath();
        //path3 = URLDecoder.decode(path3,"utf-8");
        System.out.println(path3);
    }

其中:toURI和URLDecoder.decode(path3,“utf-8”)方法解决路径中空格被"20%"替换的问题。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值