Properties 配置文件以及在项目中获取绝对路径
一、.class文件
.java文件,就是当前编写的代码文件;
.class文件,就是编译过后的文件,jvm只识别.class文件;
javac用来编译java文件生成字节码文件.class,java用来执行。
二、Properties配置文件
- Properties配置文件中,元素按map<String,String>存放。
- 呈现方式如图:
- 代码展示:
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%"替换的问题。