1.properties文件是什么 ?
properties文件是一种以properties为后缀的属性文件,这种文件以“key-value”的格式储存内容。
2.properties文件的用途
相当于定义一个变量,在这个文件中定义这些变量的值,在程序里可以调用这些变量。使用properties文件的好处是如果程序中的值需要被改动,直接改properties文件中的内容就可以了,
而不需要再去修改源代码。
3.如何在JAVA中properties文件的读取与写入
(1)properties文件的读取
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/*
* 读取properties文件格式
*
*/
public class Demo04 {
public static void main(String[] args) {
try (
//Properties格式文件的读取
//创建文件的输入流
//输入properties文件的路径
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("D:\\games\\data.properties"))) {
Properties props = new Properties();
//“将输入流”加载到Properties集合对象中
props.load(bis);
System.out.println(props.get("cn"));
System.out.println(props.get("kr"));
System.out.println(props.get("jp"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
(2)properties文件的写入
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Demo04 {
public static void main(String[] args) {
//Properties格式文件的写入
//写入方法为put
try {
Properties props = new Properties();
props.put("F1", "5641");
props.put("F2", "5641");
props.put("F3", "5641");
//使用输出流,将Properties集合中的kv键值对,写入*.Properties文件
try(BufferedOutputStream bos
= new BufferedOutputStream(
new FileOutputStream("D:\\games\\data.properties"))){
props.store(bos, "Just Do It");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}