博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA操作properties文件【要注意properties文件的路径】
阅读量:2353 次
发布时间:2019-05-10

本文共 8698 字,大约阅读时间需要 28 分钟。

文章来源:http://www.cnblogs.com/panjun-Donet/archive/2009/07/17/1525597.html

java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是"键=值"的格式,在properties
文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便。
一、properties文件
test.properties
------------------------------------------------------
#################################
#   工商报表应用IcisReport的配置文件#
#   日期:2006年11月21日 #
#################################
#
#   说明:业务系统TopIcis和报表系统IcisReport是分离的
#   可分开部署到不同的服务器上,也可以部署到同一个服务
#   器上;IcisReprot作为独立的web应用程序可以使用任何
#   的Servlet容器或者J2EE服务器部署并单独运行,也可以
#   通过业务系统的接口调用作为业务系统的一个库来应用.
#
#   IcisReport的ip
IcisReport.server.ip=192.168.3.143
#   IcisReport的端口
IcisReport.server.port=8080
#   IcisReport的上下文路径
IcisReport.contextPath=/IcisReport
------------------------------------------------------ 
Properties类的重要方法
Properties 类存在于胞 Java.util 中,该类继承自 Hashtable
1. getProperty ( String  key) ,   用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream  inStream) ,从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文
件中的所有键 - 值对。以供 getProperty ( String  key) 来搜索。
3. setProperty ( String  key, String  value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。 
4. store ( OutputStream  out, String  comments) ,   以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素
对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear () ,清除所有装载的 键 - 值对。该方法在基类中提供。
-------------------------------
二、操作properties文件的java方法 
读属性文件
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("/IcisReport.properties");
prop.load(in);
Set keyValue = prop.keySet();
for (Iterator it = keyValue.iterator(); it.hasNext();)
{
String key = (String) it.next();
}
------------------------
outputFile = new FileOutputStream(fileName);
propertie.store(outputFile, description);
outputFile.close();
-----------------------------------------------------------------------------------------
Class.getResourceAsStream ("/some/pkg/resource.properties");
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
java.util.ResourceBundle rs = java.util.ResourceBundle.getBundle("some.pkg.resource");
rs.getString("xiaofei");
-----------------------------------------------------------------------------------------
写属性文件
Configuration saveCf = new Configuration();
saveCf.setValue("min", "10");
saveCf.setValue("max", "1000");
saveCf.saveFile(".\config\save.perperties","test");
总结:javaproperties文件需要放到classpath下面,这样程序才能读取到,有关classpath实际上就是java类或者库的存放路径,在java工程中,properties放到
class文件一块。在web应用中,最简单的方法是放到web应用的WEB- INF\classes目录下即可,也可以放在其他文件夹下面,这时候需要在设置classpath环境变量的
时候,将这个文件夹路径加到 classpath变量中,这样也也可以读取到。在此,你需要对classpath有个深刻理解,classpath绝非系统中刻意设定的那个系统环境变

量,WEB-INF\classes其实也是,java工程的class文件目录也是。

发个例子大家自己看哈.

package control;

import java.io.BufferedInputStream;

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

public class TestMain {

 
 //根据key读取value
 public static String readValue(String filePath,String key) {
  Properties props = new Properties();
        try {
         InputStream in = new BufferedInputStream (new FileInputStream(filePath));
         props.load(in);
         String value = props.getProperty (key);
            System.out.println(key+value);
            return value;
        } catch (Exception e) {
         e.printStackTrace();
         return null;
        }
 }
 
 //读取properties的全部信息
    public static void readProperties(String filePath) {
     Properties props = new Properties();
        try {
         InputStream in = new BufferedInputStream (new FileInputStream(filePath));
         props.load(in);
            Enumeration en = props.propertyNames();
             while (en.hasMoreElements()) {
              String key = (String) en.nextElement();
                    String Property = props.getProperty (key);
                    System.out.println(key+Property);
                }
        } catch (Exception e) {
         e.printStackTrace();
        }
    }

    //写入properties信息

    public static void writeProperties(String filePath,String parameterName,String parameterValue) {
     Properties prop = new Properties();
     try {
      InputStream fis = new FileInputStream(filePath);
            //从输入流中读取属性列表(键和元素对)
            prop.load(fis);
            //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
            //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
            OutputStream fos = new FileOutputStream(filePath);
            prop.setProperty(parameterName, parameterValue);
            //以适合使用 load 方法加载到 Properties 表中的格式,
            //将此 Properties 表中的属性列表(键和元素对)写入输出流
            prop.store(fos, "Update '" + parameterName + "' value");
        } catch (IOException e) {
         System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
        }
    }

    public static void main(String[] args) {

     readValue("info.properties","url");
        writeProperties("info.properties","age","21");
        readProperties("info.properties" );
        System.out.println("OK");
    }

 发个例子大家自己看哈.

package control;

import java.io.BufferedInputStream;

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

public class TestMain {

 
 //根据key读取value
 public static String readValue(String filePath,String key) {
  Properties props = new Properties();
        try {
         InputStream in = new BufferedInputStream (new FileInputStream(filePath));
         props.load(in);
         String value = props.getProperty (key);
            System.out.println(key+value);
            return value;
        } catch (Exception e) {
         e.printStackTrace();
         return null;
        }
 }
 
 //读取properties的全部信息
    public static void readProperties(String filePath) {
     Properties props = new Properties();
        try {
         InputStream in = new BufferedInputStream (new FileInputStream(filePath));
         props.load(in);
            Enumeration en = props.propertyNames();
             while (en.hasMoreElements()) {
              String key = (String) en.nextElement();
                    String Property = props.getProperty (key);
                    System.out.println(key+Property);
                }
        } catch (Exception e) {
         e.printStackTrace();
        }
    }

    //写入properties信息

    public static void writeProperties(String filePath,String parameterName,String parameterValue) {
     Properties prop = new Properties();
     try {
      InputStream fis = new FileInputStream(filePath);
            //从输入流中读取属性列表(键和元素对)
            prop.load(fis);
            //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
            //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
            OutputStream fos = new FileOutputStream(filePath);
            prop.setProperty(parameterName, parameterValue);
            //以适合使用 load 方法加载到 Properties 表中的格式,
            //将此 Properties 表中的属性列表(键和元素对)写入输出流
            prop.store(fos, "Update '" + parameterName + "' value");
        } catch (IOException e) {
         System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
        }
    }

    public static void main(String[] args) {

     readValue("info.properties","url");
        writeProperties("info.properties","age","21");
        readProperties("info.properties" );
        System.out.println("OK");
    }
}

自己实验:<依据key获取对应的value>2014-12-20-20:30

①student.properties文件放在项目的根目录下可以被下面的路径识别,放在src目录下有点问题,

②java.util.Properties对象在读取properties配置文件时,出现中文乱码,使用了下面的转码

public static void readPropertiesByKey() {		Properties pro=new Properties();		File file=new File("student.properties");		InputStream is;		try {			is = new FileInputStream(file);			pro.load(is);			System.out.println(new String(pro.getProperty("name").getBytes("iso-8859-1"),"gbk"));		} catch (FileNotFoundException e) {			e.printStackTrace();		} catch (IOException e) {			e.printStackTrace();		}	}
PropertiesTest类里main函数里的写法:
public static void main(String[] args) {		Properties properties = new Properties(); 		//main函数里可以写成下面这样		InputStream inputStream = PropertiesTest.class.getResourceAsStream("/student.properties");		BufferedReader bf = new BufferedReader(new    InputStreamReader(inputStream));  		try {			properties.load(bf);		} catch (IOException e) {			e.printStackTrace();		}  		System.out.println(properties.getProperty("name"));  	}
======================================================================================================

下面文章来源:http://bu-choreography.iteye.com/blog/1136047

menu.properties放在src目录下可以被下面的路径识别;或者WebContent/WEB-INF/resource/menu.properties

问题的提出:初用properties,读取java properties文件的时候如果value是中文,会出现读取乱码的问题 
问题分析:开始以为是文件保存编码问题,把eclipse中所有的文件编码都修改成utf8,问题依然存在;把内容复制到notepad++进行utf8编码转换,问题依旧;上网搜索有人提议重写properties类或者用jdk自带的编码转换工具,嫌麻烦而且凭感觉jdk开发者不可能不考虑东亚几国的字符编码问题;因为properties文件操作的代码是参考百度文库里的一边文章的,分析其代码后,发现其用的是字节流来读取文件,具体代码如下: 

Java代码  
  1. Properties properties = new Properties();  
  2. InputStream inputStream = this.getClass().getResourceAsStream("/menu.properties");  
  3. properties.load(inputStream );  
  4. System.out.println(properties.getProperty("a"));  

因为字节流是无法读取中文的,所以采取reader把inputStream转换成reader用字符流来读取中文。代码如下: 

Java代码  
  1. Properties properties = new Properties();  
  2. InputStream inputStream = this.getClass().getResourceAsStream("/menu.properties");  
  3. BufferedReader bf = new BufferedReader(new    InputStreamReader(inputStream));  
  4. properties.load(bf);  
  5. System.out.println(properties.getProperty("a"));  


测试后能正常读取中文

你可能感兴趣的文章
iOS和Android的app界面设计规范
查看>>
Android 代码混淆异常
查看>>
Android drawable微技巧,你所不知道的drawable的那些细节
查看>>
理解Fragment生命周期
查看>>
最靠谱的禁止ViewPager滑动方法
查看>>
android错误之android.content.res.Resources$NotFoundException:
查看>>
Android监听软键盘打开收起事件(软键盘自带收起按钮)
查看>>
huffman code and encode
查看>>
exception in c++
查看>>
java并发编程lock
查看>>
阿里云技术教程系列-ECS远程连接 Linux 实例
查看>>
Linux新建用户并允许docker
查看>>
Drools Workbench 7.5.0.Final安装运行
查看>>
Docker快速部署Redis
查看>>
Spring boot shiro session cache ecache redis 共存配置
查看>>
一看就懂的设计模式--设计模式分类
查看>>
一看就懂的设计模式--模板方法
查看>>
一看就懂的设计模式--享元模式
查看>>
一看就懂的设计模式--策略模式
查看>>
spring Cloud 组建图
查看>>