---
title: "JAVA中如何读写properties文件"
author: "newchq"
date: "2010-09-29T11:48:37Z"
tags: []
categories: ["编程语言"]
slug: "java-properties"
draft: false
lastmod: "2010-09-29T11:48:37Z"
id: 774910
url: "https://newchq.iteye.com/blog/774910"
---

### Properties文件是JAVA程序特有的一种文件类型，信息以"键--值"的格式进行存放，通常将容易变化的系统参数写到此文件中。这样就可以实现快速的读和写。具体的操作方法：

读操作：

 

```
  public String readpro(String filename,String key){

             Properties props = new Properties();

             try{

                     props.load(this.getClass().getClassLoader().getResourceAsStream(filename));

                     String value = props.getProperty(key);

                     return value;

             }catch(){

                     return null;

             }

 }
```

 全部读取的方法：

   

```
Enumeration en = new props.propertyNames();

    while(en.hasMoreElements()){

             String key = (String)en.nextElement();

             String value = props.getProperty(key);

            //其他相关操作

    }

```

 

写操作：

```
public void writeProps(String filename,String name,String value){

          Properties props = new Properties();

         String path = this.getClass().getClassLoader().getResource("").getPath().substring(1);

         path=path+filename;

         try{

                  InputStream fis = new InputStream(path);

                  props.load(fis);    //从输入流中读取属性列表

                  OutputStream fos = new OutputStream(path);

                  props.setProperty(name,value);

                  props.stare(fos,"Update' "+name+" 'value");

         }catch(Exception e){

         }

}
```