java 读取和写入配置文件中的数据

1、读取配置文件中的数据,注意,此处读取的是部署的项目中的配置文件,而非项目本身的配置文件

public String getProData(String key){
		String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();  
		String rootPath = path.substring(0, path.lastIndexOf("/classes"));  
		String propertyFilePath = rootPath  
		        + "/classes/wodsy-config.properties";  
		Properties prop = new Properties();// 属性集合对象  
		FileInputStream fis;
		try {
			fis = new FileInputStream(propertyFilePath);
			prop.load(fis);// 将属性文件流装载到Properties对象中  
	        fis.close();// 关闭流  
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 属性文件输入流  
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		return prop.getProperty(key); 
	}

2、重写配置文件中某个key的value,注意同上

public void editPro(String key,String value) {  
        String path = this.getClass().getProtectionDomain().getCodeSource()  
                .getLocation().getPath();  
        String rootPath = path.substring(0, path.lastIndexOf("/classes"));  
        String propertyFilePath = rootPath  
                + "/classes/wodsy-config.properties";  
        Properties prop = new Properties();// 属性集合对象  
        FileInputStream fis;  
        try {  
            fis = new FileInputStream(propertyFilePath);// 属性文件输入流  
            prop.load(fis);// 将属性文件流装载到Properties对象中  
            fis.close();// 关闭流  
            // 修改sitename的属性值  
            prop.setProperty(key, value);  
            // 文件输出流  
            FileOutputStream fos = new FileOutputStream(propertyFilePath);  
            // 将Properties集合保存到流中  
            prop.store(fos, "Copyright (c) Boxcode Studio");  
            fos.close();// 关闭流  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    } 

3、如果要读取项目本身而非部署的项目中的配置文件中的数据,则用以下方式

1)创建一个类,调用此类就可以

import java.text.MessageFormat;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * 
 * <p>
 * 参数工具类
 * 
 * @author 
 *
 */
public class Messages {
  private static final String BUNDLE_NAME = "wodsy-config";//$NON-NLS-1$ 此为配置文件的名称wodsy-config.properties
  private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

  private Messages() {}

  public static String getString(String key) {
    try {
      return RESOURCE_BUNDLE.getString(key);
    }
    catch (MissingResourceException e) {
      return '!' + key + '!';
    }
  }

  public static String getString(String key, String[] paras) {
    // TODO Auto-generated method stub
    try {
      String message = RESOURCE_BUNDLE.getString(key);
      return MessageFormat.format(message, paras);
    }
    catch (MissingResourceException e) {
      return '!' + key + '!';
    }
  }

  public static String getString(String key, List arg) {
    // TODO Auto-generated method stub
    try {
      if (!arg.isEmpty()) {
        String[] paras = new String[arg.size()];
        for (int i = 0; i < arg.size(); i++)
          paras[i] = (String) arg.get(i);
        return getString(key, paras);
      }
      return "";
    }
    catch (MissingResourceException e) {
      return '!' + key + '!';
    }
  }
  
  public static String getStringArrayRandom(String key){
	  String values = "";
	  try{
		  values = getString(key);
//		  暂时注释掉  如运维来解决
//		  String[] array = values.split(",");
//		  int index = (int) (Math.random()*array.length);
//		  values = array[index];
	  }catch(Exception e){
		  e.printStackTrace();
	  }
	  return values;
  }
}

2)如果wodsy-config.properties中的数据存储格式是如下

serverNo=01
userAccount=10000000

如果要获取serverNo则可以用如下方式获取Messages.getString("serverNo");

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java,我们可以使用外部文件来配置参数值。常见的外部文件格式有properties文件和XML文件。 1. 使用properties文件 首先创建一个名为config.properties的文件,然后在文件设置键值对,例如: ``` username=John password=123456 ``` 然后在Java代码使用以下代码来读取配置文件: ```java import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class ConfigReader { public static void main(String[] args) { Properties prop = new Properties(); try { prop.load(new FileInputStream("config.properties")); String username = prop.getProperty("username"); String password = prop.getProperty("password"); System.out.println("Username: " + username); System.out.println("Password: " + password); } catch (IOException ex) { ex.printStackTrace(); } } } ``` 2. 使用XML文件 首先创建一个名为config.xml的文件,然后在文件设置参数值,例如: ```xml <config> <username>John</username> <password>123456</password> </config> ``` 然后在Java代码使用以下代码来读取配置文件: ```java import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; public class ConfigReader { public static void main(String[] args) { try { File configFile = new File("config.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(configFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("config"); Node nNode = nList.item(0); String username = nNode.getChildNodes().item(0).getTextContent(); String password = nNode.getChildNodes().item(1).getTextContent(); System.out.println("Username: " + username); System.out.println("Password: " + password); } catch (Exception ex) { ex.printStackTrace(); } } } ``` 这样就可以使用外部文件来配置Java程序的参数值了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值