java读取properties文件

本文介绍了一个用于操作Java中Properties配置文件的实用类。该类提供了加载、读取、修改和保存配置文件的方法,并附带了一个简单的示例来演示如何使用这个类。

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


package com.properties.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;


public class PropertiesUnit
{
private String filename;
private Properties properties;
private FileInputStream in;
private FileOutputStream out;

public PropertiesUnit()
{
properties = new Properties();
}

public PropertiesUnit(String filename)
{
this.filename = filename;
properties = new Properties();
File file = new File(filename);
try
{
in = new FileInputStream(file);

properties.load(in);
in.close();
}
catch (FileNotFoundException e)
{
System.err.println("配置文件config.properties找不到!");
e.printStackTrace();
}
catch (IOException e)
{
System.err.println("读取配置文件config.properties错误!");
e.printStackTrace();

}
}

public String getValue(String key)
{

if(properties.containsKey(key))
{
String value = properties.getProperty(key);
return value;
}
else
{
return "";
}
}

public String getValue(String fileName,String key)
{
try
{
String value="";
in = new FileInputStream(fileName);
properties.load(in);
in.close();
if(properties.containsKey(key))
{
value = properties.getProperty(key);
return value;
}
else
{
return value;
}
}
catch (FileNotFoundException e)
{
System.err.println("配置文件config.properties找不到!");
e.printStackTrace();
return "";
}
catch (IOException e)
{
System.err.println("读取配置文件config.properties错误!");
e.printStackTrace();
return "";

}
}

public void clear()
{
properties.clear();
}

public void setValue(String key,String value)
{
properties.setProperty(key,value);
}


public void saveFile(String fileName,String description)
{
try
{
out = new FileOutputStream(fileName);
properties.store(out,description);
out.close();
}
catch (FileNotFoundException e)
{
System.err.println("配置文件config.properties找不到!");
e.printStackTrace();
}
catch (IOException e)
{
System.err.println("读取配置文件config.properties错误!");
e.printStackTrace();
}
}

public static void main(String[] args)
{
PropertiesUnit pu = new PropertiesUnit("./config.properties");
String key = pu.getValue("key");
System.out.println(key);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值