您的位置:首页 > 编程语言 > Java开发

JAVA读取propertise文件内容两种方式

2016-01-08 17:58 579 查看
/**
* 读取propertise文件
* @throws IOException
*/
@Test
public void fun1() throws IOException {
/*方式一【采用反射的方式获取】:最常用的方式。常用于读取同一文件夹下的文件,若不在同一文件夹下,需要往上层找*/
InputStream inputStream = this.getClass().getResourceAsStream("../../../../config.properties");//相对路径
InputStream inputStream = this.getClaa().getClassLoader().getResourceAsStream("华融湘江的ID.txt");//获取类加载路径,读取src下的文件
Properties properties = new Properties();
properties.load(inputStream);
System.out.println(properties.getProperty("password"));;

/*方式二【采用ResourceBundle来获取本地资源】:只适用于资源文件在src下面的情况*/
ResourceBundle resourceBundle = ResourceBundle.getBundle("config");
System.out.println(resourceBundle.getString("DMUserName"));

/*方式三:以文件流的形式读取*/
Properties properties = new Properties();
properties.load(new FileReader("config.properties"));
System.out.println(properties.getProperty("password"));
System.out.println(URLDecoder.decode(this.getClass().getResource("").getPath(),"utf-8"));//获取当前类所在的项目路径
}


项目结构如下:



public class ReadText {

public static void main(String[] args) {
try {
//FileReader fileReader = new FileReader("E:/银监会/华融湘江的ID.txt");
InputStream in = ReadText.class.getClassLoader().getResourceAsStream("华融湘江的ID.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder builder = new StringBuilder("0");
String str = "";
while((str=bufferedReader.readLine()) != null) {
builder.append(","+str);
}
System.out.println(builder);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: