properties文件读写工具类

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;


public class PropertiesUtil {
    
    private String properiesName = "";

    public PropertiesUtil() {

    }
    
    public PropertiesUtil(String fileName) {
        this.properiesName = fileName;
    }
    
    /**
     * 按key获取值
     * @param key
     * @return
     */
    public String readProperty(String key) {
        String value = "";
        InputStream is = null;
        try {
            is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
            Properties p = new Properties();
            p.load(is);
            value = p.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return value;
    }

    /**
     * 获取整个配置信息
     * @return
     */
    public Properties getProperties() {
        Properties p = new Properties();
        InputStream is = null;
        try {
            is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return p;
    }

    /**
     * key-value写入配置文件
     * @param key
     * @param value
     */
    public void writeProperty(String key, String value) {
        InputStream is = null;
        OutputStream os = null;
        Properties p = new Properties();
        try {
            is = new FileInputStream(properiesName);
//            is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);
            p.load(is);
//            os = new FileOutputStream(PropertiesUtil.class.getClassLoader().getResource(properiesName).getFile());
            os = new FileOutputStream(properiesName);

            p.setProperty(key, value);
            p.store(os, key);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
                if (null != os)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        // sysConfig.properties(配置文件)
        PropertiesUtil p = new PropertiesUtil("sysConfig.properties");
        System.out.println(p.getProperties().get("db.url"));
        System.out.println(p.readProperty("db.url"));
        PropertiesUtil q = new PropertiesUtil("resources/sysConfig.properties");
        q.writeProperty("myUtils", "wang");
        System.exit(0);
    }

}

Properties类

public class Properties extends Hashtable<Object,Object>

Properties类表示一组持久的属性。 Properties可以保存到流中或从流中加载。 属性列表中的每个键及其对应的值都是一个字符串。

这个类是线程安全的:多个线程可以共享一个Properties对象,而不需要外部同步。

构造方法

Constructor and Description
Properties()
 
创建一个没有默认值的空属性列表。

Properties(Properties defaults)

创建具有指定默认值的空属性列表。

方法

String

getProperty(String key)

在属性列表中,通过指定的键搜索属性。
String

getProperty(String key, String defaultValue)

在属性列表中,通过指定的键搜索属性。
void

list(PrintStream out)

将此属性列表打印到指定的输出流。
void

list(PrintWriter out)

将此属性列表打印到指定的输出流。
void

load(InputStream inStream)

从输入字节流读取属性列表(键和元素对)。
void

load(Reader reader)

以简单的线性格式从输入字符流读取属性列表(关键字和元素对)。
void

loadFromXML(InputStream in)

将指定输入流中的XML文档表示的所有属性加载到此属性表中。
Enumeration<?>

propertyNames()

返回此属性列表中所有键的枚举,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。
Object

setProperty(String key, String value)

致电 Hashtable方法 put,(即添加键值对到properties文件
void

store(OutputStream out, String comments)

将此属性列表(键和元素对)写入此 Properties表中,以适合于使用 load(InputStream)方法加载到 Properties表中的格式输出流。
void

store(Writer writer, String comments)

将此属性列表(键和元素对)写入此 Properties表中,以适合使用 load(Reader)方法的格式输出到输出字符流。
void

storeToXML(OutputStream os, String comment)

发出表示此表中包含的所有属性的XML文档。
void

storeToXML(OutputStream os, String comment, String encoding)

使用指定的编码发出表示此表中包含的所有属性的XML文档。
Set<String>

stringPropertyNames()

返回此属性列表中的一组键,其中键及其对应的值为字符串,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。  

 应用1

      //加载properties配置文件===>Properties
            Properties properties = new Properties();
            InputStream in = new FileInputStream("src/bean.properties");
            properties.load(in);
            //根据key到配置文件中获取对应的value
            String classname = properties.getProperty(key);

 应用二

String BUCKET_NAME = PropertiesUtil.getProperty("fileOperator.properties","BucketName"); 

 自定义PropertiesUtil类如下

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class PropertiesUtil {
    public PropertiesUtil() {
    }
   //加载输入流,返回Propeties
    public static Properties load(InputStream is) throws IOException {
        Properties prop = new Properties();
        prop.load(is);
        return prop;
    }
  //通过文件路径加载文件,形成输入流,加载输入流,返回properties
    public static Properties load(String path) throws IOException {
        InputStream is = PropertiesUtil.class.getClassLoader().getResourceAsStream(path);
        if (is == null) {
            throw new IOException(path + " 文件找不到。");
        } else {
            Properties var2;
            try {
                var2 = load(is);
            } finally {
                IOUtils.closeQuietly(is);
            }

            return var2;
        }
    }

    public static void update(String path, Map<String, String> kvMap) throws IOException {
        URL url = PropertiesUtil.class.getResource(path);

        try {
            if (url != null && null != url.toURI()) {
                String absolutePath = url.toURI().getPath();
                updateAbsolutePath(absolutePath, kvMap);
            }
        } catch (URISyntaxException var4) {
            var4.printStackTrace();
        }

        throw new IOException("file: " + path + " can not found.");
    }

    public static void updateAbsolutePath(String absolutePath, Map<String, String> kvMap) throws IOException {
        File propFile = new File(absolutePath);
        InputStream in = null;
        FileOutputStream out = null;

        try {
            if (!propFile.exists()) {
                propFile.createNewFile();
            }

            in = FileUtils.openInputStream(propFile);
            Properties props = load((InputStream)in);
            Set<Entry<String, String>> kvSet = kvMap.entrySet();
            Iterator i$ = kvSet.iterator();

            while(i$.hasNext()) {
                Entry<String, String> entry = (Entry)i$.next();
                props.setProperty((String)entry.getKey(), (String)entry.getValue());
            }

            out = FileUtils.openOutputStream(propFile);
            props.store(out, (String)null);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
  //通过加载文件,指定key,获得value
    public static String getProperty(String path, String key) throws NotFoundException {
        try {
            Properties pro = load(path);
            return pro.getProperty(key);
        } catch (IOException var4) {
            String message = "获取资源文件" + path + "的key(" + key + ")失败,原因:" + var4.getCause();
            Logger.errorX(PropertiesUtil.class, message);
            throw new NotFoundException(message);
        }
    }
}
原文地址:https://www.cnblogs.com/lvhouhou/p/11979785.html