- 资源文件
资源文件是以 .properties 为后缀的文本文件。
资源文件还是一个 Key-Value 的文本文件。一定要符合 Map 接口的格式。
在资源文件中所有内容都是如下格式编写的: key=value 。
Java 文件中的一个中文转码的工具是:JAVA_HOME/bin/native2ascii.exe 。
- Properties 类
Properties 类是用来专门操作资源文件的类。
Properties 是 Map 接口的一个实现类。
Properties 也是一种 Key-Value 的集合类。
我们使用 Properties 对象来加载资源文件中的内容;加载的过程需要使用到流对象进行文件加载。
- 构造方法
public Properties()
//创建了一个空的Properties对象。
Properties properties = new Properties();
- 将一个资源文件(.properties)中的内容全部加载到 Properties 对象中。
public void load(InputStream inStream) throws IOException
从输入字节流读取属性列表(键和元素对)。
//加载资源文件
InputStream is = new FileInputStream("F:\\20230131-tu3\\src\\IOProj01\\src\\test.properties");
properties.load(is);
优化路径:在使用流对象时,不要使用绝对路径。使用当前类的路径。
InputStream is = PropertiesTest.class.getResourceAsStream("/test.properties");
properties.load(is);
//getResourceAsStream()基于当前类的路径位置去创建流对象。
//表示的是类路径的根目录。src是源文件的根目录
- 获取资源文件中的值。按 Key 取 Value
public String getProperty(String key)
//使用此属性列表中指定的键搜索属性。
//可以从Properties对象中获取资源文件中的内容。按Key取Value
String username = properties.getProperty("username");
System.out.println(username);
String password = properties.getProperty("password");
System.out.println(password);
封装操作资源文件的工具类 :
/**
* 这是一个封装操作资源文件的工具类
*/
public class PropertiesUtils {
private final static Properties PROPERTIES = new Properties();
static {
//加载资源文件
try(InputStream is = PropertiesUtils.class.getResourceAsStream("/test.properties")
) {
PROPERTIES.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 按Key取Value的方法
* @param key 关键字
* @return Value值,如果没有对应的Key,返回null
*/
public static String getProperty(String key){
return PROPERTIES.getProperty(key);
}
}
- MD5加密
adminPass=123456 。这个没有任何安全性。
使用MD5加密的工具类实现对密码的加密操作。
public static void main(String[] args) {
String pass = "123456";
String md5Pass = MD5_Encoding.getMD5(pass); //调用MD5类中的方法实现加密
System.out.println(md5Pass);
}