参考引自:https://blog.csdn.net/qq_27093465/article/details/70765870
根据自己问题解决:
package com.property;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* 读取配置文件的内容
* @author Admin
*
*/
public class propertiesFile {
public static String read(String key) {
Properties pps = new Properties();
InputStream in = null;
try {
// 读取config文件
/*File file = new File("C:\\Users\\Administrator\\workspace\\property\\config.properties");
in = new BufferedInputStream(new FileInputStream(file));
pps.load(in);// 加载属性列表
*/
File file = new File("C:\\Users\\Administrator\\workspace\\property\\config.properties");
in = new BufferedInputStream(new FileInputStream(file));
//prop.load(in);//直接这么写,如果properties文件中有汉字,则汉字会乱码。因为未设置编码格式。
pps.load(new InputStreamReader(in, "utf-8"));
if (pps.containsKey(key)) {
String value = pps.getProperty(key);
return value; // 返回读取的内容
} else {
System.out.println("没有读取到"+key);
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
propertiesFile pf = new propertiesFile();
String ss = pf.read("key");
System.out.println(ss);
}
}
package com.property;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ProUtil {
/**
* 1.确定并读取配置文件
* 2.封装getProperty方法
* */
private Properties prop;
private String filePath;
/*
* 构造方法
**/
//初始化new ProUtil是从外部传回一个properties文件的路径
public ProUtil(String filePath){
//外部文件路径赋值给当前类的文件路径
this.filePath=filePath;
//读取文件属性
this.prop=readProperties();
}
/**
* 读取配置文件
* */
private Properties readProperties() {
// 创建一个Properties
Properties properties=new Properties();
try{
//使用文件读取并且使用properties文件进行加载出来
InputStream inputStream=new FileInputStream(filePath);
BufferedInputStream bis=new BufferedInputStream(inputStream);
//BufferedReader bis = new BufferedReader(new FileReader("E:/config.properties"));
properties.load(bis);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return properties;
}
/**
* 封装配置文件中的getProperty方法
* */
public String getPro(String key){
//判断properties文件中是否包含key信息
if(prop.containsKey(key)){
String browser=prop.getProperty(key);
return browser;
}else{
System.out.println("你获取的值不存在");
return "";
}
}
}