0223-资源文件、MD5加密

文章介绍了如何使用Java的Properties类操作以.properties为后缀的资源文件,包括加载文件内容、按Key取Value的方法。同时,文中提到了资源文件的路径优化,以及封装操作资源文件的工具类。此外,还讨论了MD5加密在保护密码安全性方面的作用,提供了一个简单的MD5加密工具类的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 资源文件

资源文件是以 .properties 为后缀的文本文件。

资源文件还是一个 Key-Value 的文本文件。一定要符合 Map 接口的格式。

在资源文件中所有内容都是如下格式编写的: key=value

在这里插入图片描述
Java 文件中的一个中文转码的工具是:JAVA_HOME/bin/native2ascii.exe 。


  • Properties 类

Properties 类是用来专门操作资源文件的类。
Properties 是 Map 接口的一个实现类。
Properties 也是一种 Key-Value 的集合类。

我们使用 Properties 对象来加载资源文件中的内容;加载的过程需要使用到流对象进行文件加载。

  1. 构造方法
public Properties()

//创建了一个空的Properties对象。
Properties properties = new Properties();
  1. 将一个资源文件(.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是源文件的根目录
  1. 获取资源文件中的值。按 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);
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值