java-- properties总结

java-- properties总结

分类: Java   304人阅读  评论(0)  收藏  举报

篇章一:Loading Properties from XML

XML 属性文档具有以下 DOCTYPE 声明: <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> 注意,导入或导出属性时不 访问系统 URI (http://java.sun.com/dtd/properties.dtd);该系统 URI 仅作为一个惟一标识 DTD 的字符串:
   

[xhtml]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.  <!-- DTD for properties -->  
  3.  <!ELEMENT properties ( comment?, entry* ) >  
  4.  <!ATTLIST properties version CDATA #FIXED "1.0">  
  5.  <!ELEMENT comment (#PCDATA) > //注释  
  6.  <!ELEMENT entry (#PCDATA) > //值  
  7.  <!ATTLIST entry key CDATA #REQUIRED> //key  

下面给出一个实例:
   
[xhtml]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.  <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  
  3.  <properties>  
  4.  <comment>Hi</comment>  
  5.  <entry key="foo">bar</entry>  
  6.  <entry key="fu">baz</entry>  
  7.  </properties>  
  8.    

下面运用loadFromXML(InputStream is)读取xml:

[java]  view plain copy
  1. import java.util.*;  
  2. import java.io.*;  
  3.    
  4. public class LoadSampleXML {  
  5.     public static void main(String args[]) throws Exception {  
  6.       Properties prop = new Properties();  
  7.       FileInputStream fis =  
  8.         new FileInputStream("sampleprops.xml");  
  9.       prop.loadFromXML(fis);  
  10.       prop.list(System.out);//将属性列表输出到指定的输出流  
  11.       System.out.println(" The foo property: " +  
  12.           prop.getProperty("foo"));  
  13.     }  
  14. }  

 下面运用storeToXML(OutputStream os, String comment)方法来创建xml:

[java]  view plain copy
  1. import java.util.*;  
  2. import java.io.*;  
  3.    
  4. public class StoreXML {  
  5.     public static void main(String args[]) throws Exception {  
  6.       Properties prop = new Properties();  
  7.       prop.setProperty("one-two""buckle my shoe");  
  8.       prop.setProperty("three-four""shut the door");  
  9.       prop.setProperty("five-six""pick up sticks");  
  10.       prop.setProperty("seven-eight""lay them straight");  
  11.       prop.setProperty("nine-ten""a big, fat hen");  
  12.       FileOutputStream fos =  
  13.         new FileOutputStream("rhyme.xml");  
  14.       prop.storeToXML(fos, "Rhyme");  
  15. //传递一个输出流及一个注释的String  
  16.       fos.close();  
  17.     }  
  18. }  

输出打印的结果为:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Rhyme</comment>
<entry key="seven-eight">lay them straight</entry>
<entry key="five-six">pick up sticks</entry>
<entry key="nine-ten">a big, fat hen</entry>
<entry key="three-four">shut the door</entry>
<entry key="one-two">buckle my shoe</entry>
</properties>

为什么会选择把properties和xml关联起来?
J2SE1.5以前的版本要求直接使用XML解析器来装载配置文件并存储设置。虽然这并非是一件困难的事情,并且解析器是平台的标准部分,但是额外的工作总是有点让人烦。最近更新的java.util.Properties类现在提供了一种为程序装载和存储设置的更容易的方法:loadFromXML(InputStream is)和storeToXML(OutputStream os, String comment)方法。使用 XML 文件还是使用老式的 a=b 类型的文件完全取决于您自己。老式文件从内存的角度看肯定是轻量级的。不过,由于 XML 的普遍使用,人们会期望 XML 格式流行起来,因为它已经被广泛使用了,只不过没有用到 Properties 对象。
不过在我看来properties同xml一样,引用API中的一句话:“它将资源包中大部分(如果不是全部)特定于语言环境的信息隔离开来。”,让我们可以轻松的进行修改及动态载入。
篇章二:更好理解它的方法

在开始这一篇章的讲解之前,我们先提一下两个类:
FileInputStream类:一个文件字节输入流,从中可以读出一个字节或一批字节
FileOutputStream类:一个文件字节输出流,可向流中写一个字节或一批字节
第一个方法:public void load(InputStream inStream) throws IOException从输入流中读取属性列表(键和元素对)。
第二个方法:public void store(OutputStream out,String comments)throws IOException将load方法读取到的属性列表写入out流中。这里的comments是注释
下面我们用代码来说明:
这里我们已经创建了两个properties文件:
文件1:
#test.properties
1=a
2=b
3=c
文件二:
#temp.test.properties
today=Monday
tomorrow=Tuesday
下面我们将就Store方法进行讨论

[java]  view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.util.Properties;  
  9. public class propertiesdemo{  
  10. Properties prop = new Properties();  
  11.      public static void main(String args[]){  
  12.         propertiesdemo demo=new propertiesdemo();  
  13.         demo.init();  
  14.    }   
  15. private void init() {  
  16. try {   
  17.         InputStream fis = new FileInputStream("G:/Sunny/Keta/JTest/src/com/build/test.properties");   
  18. //从输入流中读取属性列表(键和元素对)   
  19.         prop.load(fis);   
  20. //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。   
  21. //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。   
  22.       OutputStream fos = new FileOutputStream("G:/Sunny/Keta/JTest/src/com/build/temp.properties");   
  23.       prop.setProperty("2","w");   
  24.  //prop.setProperty("3","sorry");   
  25.  //以适合使用 load 方法加载到 Properties 表中的格式, 将此Properties 表中的属性列表(键和元素对)写入输出流   
  26.       prop.store(fos, "Update '" + 2 + "' value  ");   
  27.           }catch (IOException e) {   
  28.                                       e.printStackTrace();   
  29.                   System.err.println("Visit " + 2 + " for updating " + "w" + " value error");   
  30.              }  
  31.               
  32.   
  33.                    }  
  34.          }  


演示代码的结果是test.properties中的内容不变
而temp.properties中的内容如下:
#Update '2' value 
#Sun Dec 02 00:16:31 CST 2007
3=c
2=w
1=a
我们可以发现当我们得到test.properties的属性列表后并调用setProperty对属性列表做出修改后得到的新的属性列表覆盖了temp.properties的内容。输入顺序正如api文档所述:如果 comments 变量非 null,则首先将 ASCII # 字符、注释字符串和一个行分隔符写入输出流。因此,该 comments 可用作一个标识注释。接下来总是写入一个注释行,该行包括一个 ASCII # 字符、当前的日期和时间(就好像使用 Date 的 toString 方法获取当前时间一样)和一个由 Writer 生成的行分隔符。然后将此 Properties 表中的所有项写入 out,一次一行。
如果只想在temp.properties的后面添加而不希望覆盖 ,我们只需这样写new FileOutputStream(String name,true)即可。
下面我们将写一个读properties的模块:


 

[java]  view plain copy
  1. Enumeration<?> enumeration = prop.propertyNames();  
  2.   while (enumeration.hasMoreElements()) {  
  3.    String propertyname = enumeration.nextElement().toString();  
  4.    System.out.println(propertyname + ":"  
  5.      + prop.getProperty(propertyname, "unknown"));当然在运用它时你还要把它补充完整。如果你够仔细,你将会在前面的代码中找到怎样同过key得到value的方法  

篇章3:如何解决中文乱码的问题
如果你的properties文件中含有中文,在不做任何处理的情况下你得到的将是一连串的问号。在那一步中产生了这一问题呢?在API中我们可以在load方法中阅读这一段:假定该流使用 ISO 8859-1 字符编码;也就是每个字节是一个 Latin1 字符。对于非 Latin1 的字符和某些特殊字符,可以使用与字符和字符串字面值所用的类似转义序列。
也就是说我们要把汉字转换为/uXXXX。
如何做到这一点,我这里有两个办法:
办法一:使用native2ascii 命令(具体用法csdn上可以搜到很多)。
办法二:重写native2ascii命令
对于办法二,我重写了一个模块,基本实现native2ascii的转义功能:
 

[java]  view plain copy
  1. package com.build;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.IOException;  
  7.   
  8. /** 
  9.   *author:Aivin Ray 
  10.   *data:2007-12-01 
  11.   **/  
  12.   
  13. public class ToUnicode  
  14. {     
  15.   // 将字符串转unicode  
  16.   public static String convert(String s) {  
  17.     String unicode = "";  
  18.     char[] charAry = new char[s.length()];  
  19.     for(int i=0; i<charAry.length; i++) {  
  20.       charAry[i] = (char)s.charAt(i);  
  21.       if(Character.isLetter(charAry[i])&&(charAry[i]>255))  
  22.            unicode+="/u" + Integer.toString(charAry[i], 16);  
  23.       else  
  24.            unicode+=charAry[i];  
  25.     }  
  26.     return unicode;  
  27.   }  
  28. //读文件   
  29.   public static String readFile(String filePath) throws IOException, FileNotFoundException {   
  30.               String result = null;   
  31.               File file = new File(filePath);   
  32.               if (file.exists()) {   
  33.                            FileInputStream fis = new FileInputStream(file);   
  34.             byte[] b = new byte[fis.available()];   
  35.             //从输入流中读取b.length长的字节并将其存储在缓冲区数组 b 中。  
  36.             fis.read(b);   
  37.             //使用指定的字符集解码指定的字节数组  
  38.             result = new String(b, "gbk");   
  39.             fis.close();   
  40.         }   
  41.         return convert(result);   
  42.     }   
  43. }   

在写这个模块之前我使用的是这个模块当然这个模块经常被用来处理jsp的中文字符问题
代码如下:

[java]  view plain copy
  1. package com.build;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.PropertyResourceBundle;  
  5. import java.io.*;  
  6. /** 
  7.   *author:Aivin Ray 
  8.    *publish data:2007-12-1 
  9.    *tips:the segment of my project 
  10.    **/  
  11. public class ProperitiesRead {  
  12.     private static PropertyResourceBundle Config = null;  
  13.   
  14.     private static final String CONFIGKEY_House_PREFIX = "HouseGrade";  
  15.   
  16.     ArrayList<String> list = new ArrayList<String>();  
  17.   
  18.     public ProperitiesRead(String file) {  
  19.         setconfigfile(getClass().getResourceAsStream(file));  
  20.     }  
  21.   
  22.     public boolean setconfigfile(InputStream in) {  
  23.         boolean is = true;  
  24.         if (in != null) {  
  25.             try {  
  26.                 Config = new PropertyResourceBundle(in);  
  27.             } catch (IOException e) {  
  28.                 // TODO 自动生成 catch 块  
  29.                 is = false;  
  30.             }  
  31.             if (is) {  
  32.                 try {  
  33.                     int index = 0;  
  34.                     while (true) {  
  35.                                            String keyvalue1 = getkeyvalue(Config.getString(CONFIGKEY_House_PREFIX + index))  
  36.                                            list1.add(keyvalue1);  
  37.         index++;  
  38.                     }  
  39.                 } catch (Exception ex) {  
  40.   
  41.                 }  
  42.             }  
  43.         }  
  44.         return is;  
  45.     }  
  46.   
  47.     public ArrayList<String> getHouseGrade() {  
  48.         return list;  
  49.     }  
  50.   
  51.        /*解决乱码问题,可以提取出来做为模块使用*/      
  52.     public String getkeyvalue(String key) {  
  53.         String keyvalue = null;  
  54.         try {  
  55.             keyvalue = new String(key.getBytes("ISO-8859-1"), "gb2312");  
  56.         } catch (UnsupportedEncodingException e) {  
  57.             e.printStackTrace();  
  58.         }  
  59.         return keyvalue;  
  60.   
  61.     }  
  62.   
  63. }  

篇章4:读取Properties文件三种方法 

1。使用java.util.Properties类的load()方法
示例:InputStream in=new BufferedInputStream(new FileInputStream(name));
或者 InputStream in=JProperties.class.getResourceAsStream(name);
或者 InputStream in=JProperties.class.getClassLoader().getResourceAsStream(name);
或者 InputStreamin=ClassLoader.getSystemResourceAsStream(name);
然后: 
Properties p=new Properties();
p.load(in);
2。使用java.util.ResourceBundle类的getBundle()方法
示例:ResourceBundlerb=ResourceBundle.getBundle(name,Locale.getDefault());
3。使用java.util.PropertyResourceBundle类的构造函数
示例:InputStream in=new BufferedInputStream(new FileInputStream(name));
ResourceBundler b=new PropertyResourceBundle(in);
补充:
Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStreamin=context.getResourceAsStream(path);
Properties p=new Properties();
p.load(in);

篇章五:最后的模块——对properites值的修改


 

[java]  view plain copy
  1. package com.builder;  
  2.   
  3. /**  
  4. * @author Aivin.Ray 
  5. * @data   2007-12-1 
  6. */   
  7.   
  8. import java.io.File;   
  9. import java.io.FileInputStream;   
  10. import java.io.FileNotFoundException;   
  11. import java.io.FileOutputStream;   
  12. import java.io.IOException;   
  13. import java.io.InputStream;   
  14. import java.util.Properties;   
  15. //前一篇已介绍此方法   
  16. import com.builder.ToUnicode;   
  17.   
  18. public class CreatePro {   
  19. //读文件   
  20. public static String readFile(String filePath, String parameterName) throws IOException, FileNotFoundException {   
  21.     String result = null;   
  22.     File file = new File(filePath);   
  23.         if (file.exists()) {   
  24.         FileInputStream fis = new FileInputStream(file);   
  25.         byte[] b = new byte[fis.available()];   
  26.         fis.read(b);   
  27.         result = new String(b, "UTF-8");   
  28.         fis.close();   
  29.     }   
  30.     return result;   
  31. }   
  32. //修改后存储   
  33. public static void saveFile(String content, String path, String fileName) throws IOException {   
  34.     File f = new File(path);   
  35.     if (!f.exists()) {   
  36.         f.mkdirs();   
  37.     }   
  38.     File fn = new File(f, fileName);   
  39.     FileOutputStream fos = new FileOutputStream(fn);   
  40.     fos.write(content.getBytes());   
  41.     fos.close();   
  42. }   
  43. //删除旧文件   
  44. public static void deleteFile(String path) throws IOException {   
  45.     File f = new File(path);   
  46.     if (f.exists()) {   
  47.         f.delete();   
  48. else {   
  49.         throw new IOException("未找到相关文件");   
  50.     }   
  51. }   
  52. //执行方法   
  53. public static boolean writeProperties(String filePath, String parameterName, String parameterValue) {   
  54.     boolean flag = false;   
  55.     try {   
  56.         //取得文件所有内容   
  57.         String all = CreatePro.readFile(filePath, parameterName);   
  58.         String result = null;   
  59.         //如果配置文件里存在parameterName   
  60.         if (all.indexOf(parameterName) != -1) {   
  61.             //得到parameterName前的字节数   
  62.             int a=all.indexOf(parameterName);   
  63.             //取得以前parameterName的值   
  64.             String old = readProperties(filePath, parameterName);   
  65.             //得到parameterName值前的字节数   
  66.             int b=a+(parameterName.length()+"=".length());   
  67.             //新的properties文件所有内容为:旧的properties文件中内容parameterName+"="+新的parameterName值(parameterValue)+旧的properties文件中parameterName值之后的内容   
  68.             result=all.substring(0,a)+parameterName+"="+parameterValue+all.substring(b+ToUnicode.convert(old).length(),all.length());   
  69.         }   
  70.         //删除以前的properties文件   
  71.        CreatePro.deleteFile(filePath);   
  72.         //存储新文件到以前位置   
  73.         String[] arrPath = filePath.split("WEB-INF");   
  74.         String path = arrPath[0]+"WEB-INF/configs";   
  75.         CreatePro.saveFile(result, path, "xf.properties");   
  76.         flag=true;   
  77. catch (IOException e) {   
  78.         e.printStackTrace();   
  79.         flag=false;   
  80.     }   
  81.     return flag;   
  82. }   
  83. //读properties文件,Properties方法   
  84. public static String readProperties(String filePath, String parameterName) {   
  85.     String value = "";   
  86.     Properties prop = new Properties();   
  87.     try {   
  88.         InputStream fis = new FileInputStream(filePath);   
  89.         prop.load(fis);   
  90.         value = prop.getProperty(parameterName);   
  91.     } catch (IOException e) {   
  92.         e.printStackTrace();   
  93.     }   
  94.     return value;   
  95. }
 

这段代码是极其有意义的,它非常全面的提供了Properties的修改操作,同时删除了重复的键值。

引用自: http://blog.csdn.net/busaudio/archive/2007/12/02/1911449.aspx  作者:RayAivin














 

Java读取Properties文件的六种方法

分类: J2EE   90人阅读  评论(0)  收藏  举报
Java读取Properties文件的六种方法
Java读取properties文件

使用J2SE API读取Properties文件的六种方法

1。使用java.util.Properties类的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);

2。使用java.util.ResourceBundle类的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

3。使用java.util.PropertyResourceBundle类的构造函数
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);

4。使用class变量的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);

补充

Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);

完整的示例,可以参考附件文件
如何上传文件,谁知道请告诉以下。 只好把source都贴上来了
JProperties.java文件



package com.kindani;

//import javax.servlet.ServletContext;
import java.util.*;
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;


public class JProperties {

public final static int BY_PROPERTIES = 1;
public final static int BY_RESOURCEBUNDLE = 2;
public final static int BY_PROPERTYRESOURCEBUNDLE = 3;
public final static int BY_CLASS = 4;
public final static int BY_CLASSLOADER = 5;
public final static int BY_SYSTEM_CLASSLOADER = 6;

public final static Properties loadProperties(final String name, final int type) throws IOException {
Properties p = new Properties();
InputStream in = null;
if (type == BY_PROPERTIES) {
in = new BufferedInputStream(new FileInputStream(name));
assert (in != null);
p.load(in);
} else if (type == BY_RESOURCEBUNDLE) {
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
assert (rb != null);
p = new ResourceBundleAdapter(rb);
} else if (type == BY_PROPERTYRESOURCEBUNDLE) {
in = new BufferedInputStream(new FileInputStream(name));
assert (in != null);
ResourceBundle rb = new PropertyResourceBundle(in);
p = new ResourceBundleAdapter(rb);
} else if (type == BY_CLASS) {
assert (JProperties.class.equals(new JProperties().getClass()));
in = JProperties.class.getResourceAsStream(name);
assert (in != null);
p.load(in);
// return new JProperties().getClass().getResourceAsStream(name);
} else if (type == BY_CLASSLOADER) {
assert (JProperties.class.getClassLoader().equals(new JProperties().getClass().getClassLoader()));
in = JProperties.class.getClassLoader().getResourceAsStream(name);
assert (in != null);
p.load(in);
// return new JProperties().getClass().getClassLoader().getResourceAsStream(name);
} else if (type == BY_SYSTEM_CLASSLOADER) {
in = ClassLoader.getSystemResourceAsStream(name);
assert (in != null);
p.load(in);
}

if (in != null) {
in.close();
}
return p;

}

// ---------------------------------------------- servlet used


// ---------------------------------------------- support class


public static class ResourceBundleAdapter extends Properties {
public ResourceBundleAdapter(ResourceBundle rb) {
assert (rb instanceof java.util.PropertyResourceBundle);
this.rb = rb;
java.util.Enumeration e = rb.getKeys();
while (e.hasMoreElements()) {
Object o = e.nextElement();
this.put(o, rb.getObject((String) o));
}
}

private ResourceBundle rb = null;

public ResourceBundle getBundle(String baseName) {
return ResourceBundle.getBundle(baseName);
}

public ResourceBundle getBundle(String baseName, Locale locale) {
return ResourceBundle.getBundle(baseName, locale);
}

public ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) {
return ResourceBundle.getBundle(baseName, locale, loader);
}

public Enumeration getKeys() {
return rb.getKeys();
}

public Locale getLocale() {
return rb.getLocale();
}

public Object getObject(String key) {
return rb.getObject(key);
}

public String getString(String key) {
return rb.getString(key);
}

public String[] getStringArray(String key) {
return rb.getStringArray(key);
}

protected Object handleGetObject(String key) {
return ((PropertyResourceBundle) rb).handleGetObject(key);
}

}

}

JPropertiesTest.java文件


package com.kindani.test;

import junit.framework.*;
import com.kindani.JProperties;

//import javax.servlet.ServletContext;
import java.util.Properties;

public class JPropertiesTest extends TestCase {
JProperties jProperties;
String key = "helloworld.title";
String value = "Hello World!";

public void testLoadProperties() throws Exception {
String name = null;
Properties p = new Properties();

name = "C://IDEAP//Properties4Methods//src//com//kindani//test//LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_PROPERTIES);
assertEquals(value, p.getProperty(key));

name = "com.kindani.test.LocalStrings";
p = JProperties.loadProperties(name,JProperties.BY_RESOURCEBUNDLE);
assertEquals(value, p.getProperty(key));
assertEquals(value,((JProperties.ResourceBundleAdapter)p).getString(key));

name = "C://IDEAP//Properties4Methods//src//com//kindani//test//LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_PROPERTYRESOURCEBUNDLE);
assertEquals(value, p.getProperty(key));
assertEquals(value,((JProperties.ResourceBundleAdapter)p).getString(key));

name = "//com//kindani//test//LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_SYSTEM_CLASSLOADER);
assertEquals(value, p.getProperty(key));

name = "//com//kindani//test//LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_CLASSLOADER);
assertEquals(value, p.getProperty(key));

name = "test//LocalStrings.properties";
p = JProperties.loadProperties(name, JProperties.BY_CLASS);
assertEquals(value, p.getProperty(key));
}


}

properties文件与JPropertiesTest.java文件相同的目录下
LocalStrings.properties文件
# $Id: LocalStrings.properties,v 1.1 2000/08/17 00:57:52 horwat Exp $

# Default localized resources for example servlets
# This locale is en_US

helloworld.title=Hello World!

requestinfo.title=Request Information Example
requestinfo.label.method=Method:
requestinfo.label.requesturi=Request URI:
requestinfo.label.protocol=Protocol:
requestinfo.label.pathinfo=Path Info:
requestinfo.label.remoteaddr=Remote Address:

requestheader.title=Request Header Example

requestparams.title=Request Parameters Example
requestparams.params-in-req=Parameters in this request:
requestparams.no-params=No Parameters, Please enter some
requestparams.firstname=First Name:
requestparams.lastname=Last Name:

cookies.title=Cookies Example
cookies.cookies=Your browser is sending the following cookies:
cookies.no-cookies=Your browser isn't sending any cookies
cookies.make-cookie=Create a cookie to send to your browser
cookies.name=Name:
cookies.value=Value:
cookies.set=You just sent the following cookie to your browser:

sessions.title=Sessions Example
sessions.id=Session ID:
sessions.created=Created:
sessions.lastaccessed=Last Accessed:
sessions.data=The following data is in your session:
sessions.adddata=Add data to your session
sessions.dataname=Name of Session Attribute:
sessions.datavalue=Value of Session Attribute:

------------------------------------------------------------------------------------------------------------------------------------------------------------------

Java对properties配置文件的操作


package com.yorsun;

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

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;


public class PropertiesUnit {
private String filename;

private Properties p;

private FileInputStream in;

private FileOutputStream out;

public PropertiesUnit(String filename) {
this.filename = filename;
File file = new File(filename);
try {
in = new FileInputStream(file);
p = new Properties();
p.load(in);
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("配置文件config.properties找不到!");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("读取配置文件config.properties错误!");
e.printStackTrace();
}
}

public static String getConfigFile(HttpServlet hs) {
return getConfigFile(hs, "config.properties");
}


private static String getConfigFile(HttpServlet hs, String configFileName) {
String configFile = "";
ServletContext sc = hs.getServletContext();
configFile = sc.getRealPath("/" + configFileName);
if (configFile == null || configFile.equals("")) {
configFile = "/" + configFileName;
}
// TODO Auto-generated method stub
return configFile;
}

public void list() {
p.list(System.out);
}

public String getValue(String itemName) {
return p.getProperty(itemName);
}

public String getValue(String itemName, String defaultValue) {
return p.getProperty(itemName, defaultValue);
}

public void setValue(String itemName, String value) {
p.setProperty(itemName, value);
}

public void saveFile(String filename, String description) throws Exception {
try {
File f = new File(filename);
out = new FileOutputStream(f);
p.store(out, description);
out.close();
} catch (IOException ex) {
throw new Exception("无法保存指定的配置文件:" + filename);
}
}

public void saveFile(String filename) throws Exception{
saveFile(filename,"");
}

public void saveFile() throws Exception{
if(filename.length()==0)
throw new Exception("需指定保存的配置文件名");
saveFile(filename);
}

public void deleteValue(String value){
p.remove(value);
}

public static void main(String args[]){
String file="/eclipse/workspace/NewsTest/WEB-INF/config.properties";
// String file="D://eclipse//workspace//NewsTest//WEB-INF//config.properties";
PropertiesUnit pu=new PropertiesUnit(file);
pu.list();
}

}

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

package com.test.TestClass;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadPropertiesFile ...{

public void readPropertiesFile(String fileName) throws FileNotFoundException ...{
String str = "";
Properties prop = new Properties();

InputStream stream = null;

//读取这个类在同一包中的properties文件
//stream = getClass().getClassLoader().getResourceAsStream(fileName);
System.out.println("path:" + getClass().getResource(fileName));


//读取SRC下的的properties文件
String path = getClass().getResource("/").getPath();
stream = new BufferedInputStream(new FileInputStream(new File(path+fileName)));

try ...{
prop.load(stream);
str = prop.getProperty("localname");
System.out.println("localname:" + str);
System.out.println("properties:" + prop);
stream.close();

} catch (IOException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
}
}


public static void main(String[] args) throws FileNotFoundException ...{
// TODO Auto-generated method stub
new ReadPropertiesFile().readPropertiesFile("config.properties");

}

}

--------------------------------------------------------------------------------------------------------------------------------------

//=================sprin配置文件================================
<bean
id="userService"
class="com.thtf.ezone.ezesb.jmx.admin.service.impl.UserServiceImpl">
<property
name="filePath"
value="config/userInfo.properties" />
</bean>

//=================java文件================================

package com.thtf.ezone.ezesb.jmx.admin.service.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class UserServiceImpl implements UserService {

String filePath = null;

public void setFilePath(String filePath) {
this.filePath = filePath;
}

public static void main(String dd[])throws Exception{

Properties p = new Properties();
FileInputStream ferr=new FileInputStream((getClass().getClassLoader()
.getResource("") + filePath).toString().substring(6));// 用subString(6)去掉:file:/try{
p.load(ferr);
ferr.close();
Set s = p.keySet();
Iterator it = s.iterator();
while(it.hasNext()){
String id = (String)it.next();
String value = p.getProperty(id);
System.out.println(id+":="+value);
}
}catch(Exception e){
e.printStackTrace();
}
}
}

//==============databaseconfing.properties 文件=====================

#----------------------------------
# sql server 2000数据厍连接信息
#----------------------------------
dp.sd.DataBaseTyp=mssql
DataBaseHost=127.0.0.1:1433
DataBase=formpro
UserName=sa
PassWord=01
#----------------------------------
# mysql 数据厍连接信息
#----------------------------------
#DataBaseHost=127.0.0.1:3306
#DataBaseTyp=mysql
#DataBase=snow
#UserName=root
#PassWord=01
//==========================运行结果=======================

PassWord:=01
DataBaseHost:=127.0.0.1:1433
DataBase:=formpro
dp.sd.DataBaseTyp:=mssql
UserName:=sa

























分类:  Java2010-06-30 14:33  1607人阅读  评论(0)  收藏  举报

Properties 类已不是新东西了,它在 Java 编程的早期就有了,并且几乎没有什么变化。J2SE 的 Tiger 版本增强了这个类,不仅可以用它在单独一行中指定用等号分隔的多个键-值对,还可以用XML 文件装载和保存这些键-值对。在 驯服 Tiger的这一期文章中,John Zukowski 展示了如何驾驭这匹新一代的“役马”。请在本文对应的讨论论坛上与作者及其他读者分享您对本文的想法(您也可以单击文章顶部或底部的 讨论来访问该论坛)。


      J2SE 1.5 以前的版本要求直接使用 XML 解析器来装载配置文件并存储设置。虽然这并非是一件困难的事情,并且解析器是平台的标准部分,但是额外的工作总是有点让人烦。最近更新的 java.util.Properties 类现在提供了一种为程序装载和存储设置的更容易的方法: 
 loadFromXML(InputStream is) storeToXML(OutputStream os, String comment) 方法。 
Properties 基本知识
    如果不熟悉 java.util.Properties 类,那么现在告诉您它是用来在一个文件中存储键-值对的,其中键和值是用等号分隔的,如清单 1 所示。 
清单 1. 一组属性示例 
foo=bar
fu=baz 

     将清单 1 装载到 Properties 对象中后,您就可以找到两个键( foo 和 fu )和两个值( foo 的 bar 和 fu 的 baz )了。这个类支持带 /u 的嵌入 Unicode 字符串,但是这里重要的是每一项内容都当作 String 。 
清单 2 显示了如何装载属性文件并列出它当前的一组键和值。只需传递这个文件的 InputStream 给 load() 方法,就会将每一个键-值对添加到 Properties 实例中。然后用 list() 列出所有属性或者用 getProperty() 获取单独的属性。 
清单 2. 装载属性 
import java.util.*;
import java.io.*; 
public class LoadSample {
  public static void main(String args[]) throws Exception {
    Properties prop = new Properties();
    FileInputStream fis = 
      new FileInputStream("sample.properties");
    prop.load(fis);
    prop.list(System.out);
    System.out.println("/nThe foo property: " +
        prop.getProperty("foo"));
  }

     运行 LoadSample 程序生成如清单 3 所示的输出。注意 list() 方法的输出中键-值对的顺序与它们在输入文件中的顺序不一样。 Properties 类在一个散列表(hashtable,事实上是一个 Hashtable 子类)中储存一组键-值对,所以不能保证顺序。 
清单 3 . LoadSample 的输出 
-- listing properties --
fu=baz
foo=bar 
The foo property: bar 

XML 属性文件
这里没有什么新内 容。 Properties 类总是这样工作的。不过,新的地方是从一个 XML 文件中装载一组属性。它的 DTD 如清单 4 所示。 
清单 4. 属性 DTD 
<?xml version="1.0" encoding="UTF-8"?>
<!-- DTD for properties -->
<!ELEMENT properties ( comment?, entry* ) >
<!ATTLIST properties version CDATA #FIXED "1.0">
<!ELEMENT comment (#PCDATA) >
<!ELEMENT entry (#PCDATA) >
<!ATTLIST entry key CDATA #REQUIRED> 
    如果不想细读 XML DTD,那么可以告诉您它其实就是说在外围 <properties> 标签中包装的是一个 <comment> 标签,后面是任意数量的 <entry> 标签。对每一个 <entry> 标签,有一个键属性,输入的内容就是它的值。清单 5 显示了 清单 1中的属性文件的 XML 版本是什么样子的。 
清单 5. XML 版本的属性文件 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd ">
<properties>
<comment>Hi</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>
</properties> 

如果清单 6 所示,读取 XML 版本的 Properties 文件与读取老格式的文件没什么不同。 
清单 6. 读取 XML Properties 文件 
import java.util.*;
import java.io.*; 
public class LoadSampleXML {
  public static void main(String args[]) throws Exception {
    Properties prop = new Properties();
    FileInputStream fis =
      new FileInputStream("sampleprops.xml");
    prop.loadFromXML(fis);
    prop.list(System.out);
    System.out.println("/nThe foo property: " +
        prop.getProperty("foo"));
  }


关于资源绑定的说明 
      虽然 java.util.Properties 类现在除了支持键-值对,还支持属性文件作为 XML 文件,不幸的是,没有内置的选项可以将 ResourceBundle 作为一个 XML 文件处理。是的, PropertyResourceBundle 不使用 Properties 对象来装载绑定,不过装载方法的使用是硬编码到类中的,而不使用较新的 loadFromXML() 方法。 

运行清单 6 中的程序产生与原来的程序相同的输出,如 清单 2所示。 
保存 XML 属性
新的 Properties 还有一个功能是将属性存储到 XML 格式的文件中。虽然 store() 方法仍然会创建一个类似 清单 1 所示的文件,但是现在可以用新的 storeToXML() 方法创建如 清单 5 所示的文件。只要传递一个 OutputStream 和一个用于注释的 String 就可以了。清单 7 展示了新的 storeToXML() 方法。 
清单 7. 将 Properties 存储为 XML 文件 
import java.util.*;
import java.io.*; 
public class StoreXML {
  public static void main(String args[]) throws Exception {
    Properties prop = new Properties();
    prop.setProperty("one-two", "buckle my shoe");
    prop.setProperty("three-four", "shut the door");
    prop.setProperty("five-six", "pick up sticks");
    prop.setProperty("seven-eight", "lay them straight");
    prop.setProperty("nine-ten", "a big, fat hen");
    FileOutputStream fos =
      new FileOutputStream("rhyme.xml");
    prop.storeToXML(fos, "Rhyme");
    fos.close();
  }


运行清单 7 中的程序产生的输出如清单 8 所示。 
清单 8. 存储的 XML 文件 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd ">
<properties>
<comment>Rhyme</comment>
<entry key="seven-eight">lay them straight</entry>
<entry key="five-six">pick up sticks</entry>
<entry key="nine-ten">a big, fat hen</entry>
<entry key="three-four">shut the door</entry>
<entry key="one-two">buckle my shoe</entry>
</properties> 
结束语 
     使用 XML 文件还是使用老式的 a=b 类型的文件完全取决于您自己。老式文件从内存的角度看肯定是轻量级的。不过,由于 XML 的普遍使用,人们会期望 XML 格式流行起来,因为它已经被广泛使用了,只不过没有用到 Properties 对象。选择完全在您。分析软件包 private XMLUtils 类的源代码以获得关于所使用的 XML 解析的更多信息。 
PTest.java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
 * 实现properties文件的读取
 * @author bbflyerwww
 * @date 2006-08-02
 */
public class PTest {
    public static void main(String[] args) {
        try {
            long start = System.currentTimeMillis();
            InputStream is = new FileInputStream("conf.properties");
            Properties p = new Properties();
            p.load(is);
            is.close();
            System.out.println("SIZE : " + p.size());
            System.out.println("homepage : " + p.getProperty("homepage"));
            System.out.println("author : " + p.getProperty("author"));
         &nbp;  System.out.println("school : " + p.getProperty("school"));
            System.out.println("date : " + p.getProperty("date"));
            long end = System.currentTimeMillis(); 
            System.out.println("Cost : " + (end - start));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

conf.properties
# Configuration file
homepage = http://hi.baidu.com/bbflyerwww 
author = bbflyerwww
school = WuHan University
date = 2006-08-02 
Result
SIZE:4
homepage : http://hi.baidu.com/bbflyerwww 
author : bbflyerwww
school : WuHan University
date : 2006-08-02
Cost : 0
 

======================================================================== 
 

package com.adrop.util;

 

import java.io.*;

import java.util.Properties;

import javax.servlet.http.*;

import javax.servlet.*;

import javax.servlet.jsp.*;

 

public class PropertiesUtil {

  private String fileName;

  private Properties p;

  private FileInputStream in;

  private FileOutputStream out;

  /**

   * 根据传进的文件名载入文件

   * @param fileName String

   */

  public PropertiesUtil(String fileName) {

    this.fileName=fileName;

    File file = new File(fileName);

    try {

      in = new FileInputStream(file);

      p = new Properties();

      // 载入文件

      p.load(in);

      in.close();

    }

    catch (FileNotFoundException e) {

      System.err.println(" 配置文件 config.properties 找不到!! ");

       e.printStackTrace();

    }

    catch (Exception e) {

      System.err.println(" 读取配置文件 config.properties 错误!! ");

      e.printStackTrace();

    }

  }

 

  /**

   * 配置文件一律为 config.propertities , 并且统一放在 web应用的根目录下。

   * @return String

   */

  public static String getConfigFile(HttpServlet hs) {

 

    return getConfigFile(hs,"config.properties");

  }

  /**

   * 在 servlet 中使用 , 直接用 this 作为参数 ,HttpServlet 类型

   * 根据配置文件名从当前 web 应用的根目录下找出配置文件

   * @param hs HttpServlet

   * @param configFileName String 配置文件名字

   * @return String

   */

  public static String getConfigFile(HttpServlet hs, String configFileName) {

    String configFile = "";

    ServletContext sc = hs.getServletContext();

    configFile = sc.getRealPath("/" + configFileName);

    if (configFile == null || configFile.equals("")) {

      configFile = "/" + configFileName;

    }

    return configFile;

  }

  /**

   * jsp 中用 pageContext 作参数

   * @param hs PageContext

   * @param configFileName String 配置文件名字

   * @return String

   */

  public static String getConfigFile(PageContext hs, String configFileName) {

    String configFile = "";

    ServletContext sc = hs.getServletContext();

    configFile = sc.getRealPath("/" + configFileName);

    if (configFile == null || configFile.equals("")) {

      configFile = "/" + configFileName;

    }

    return configFile;

  }

 

  /**

   * 列出所有的配置文件内 容<

/span>

   */

  public void list() {

    p.list(System.out);

  }

 

  /**

   * 指定配置项名称,返回配置 值

   * @param itemName String

   * @return String

   */

  public String getValue(String itemName){

    return p.getProperty(itemName);

  }

 

  /**

   * 指定配置项名称和默认值, 返回配置值

   * @param itemName String

   * @param defaultValue String

   * @return String

   */

  public String getValue(String itemName,

                         String defaultValue){

    return p.getProperty(itemName,defaultValue);

  }

 

  /**

   * 设置配置项名称及其值

   * @param itemName String

   * @param value String

   */

  public void setValue(String itemName,String value){

    p.setProperty(itemName,value);

    return;

  }

 

  /**

   * 保存配置文件,指定文件名 和抬头描述

   * @param fileName String

   * @param description String

   * @throws Exception

   */

  public void saveFile(String fileName,String description)throws Exception{

    try {

      File f=new File(fileName);

      out

          = new FileOutputStream(f);

      p.store(out, description);// 保存文件

      out.close();

    }

t">    catch (IOException ex) {

      throw new Exception

          (" 无法保存指 定的配置文件 :"+fileName);

    }

  }

 

  /**

   * 保存配置文件,指定文件名

   * @param fileName String

   * @throws Exception

   */

  public void saveFile(String fileName)

      throws Exception {

    saveFile(fileName,"");

  }

 

  /**

   * 保存配置文件,采用原文件 名

   * @throws Exception

    */

  public void saveFile() throws Exception {

    if(fileName.length()==0)

      throw new Exception

          (" 需指定保存 的配置文件名 ");

    saveFile(fileName);

  }

  /**

   * 删除一个属性

   * @param value String

   */

  public void deleteValue(String value){

    p.remove(value);

  }

  /**

   * main method for test

   * @param args String[]

   */

  public static void main(String[] args) {

    String file = "f://p.properties";

    PropertiesUtil pu = new PropertiesUtil(file);

    pu.list();

  }

}

g="0">

 
Re:用java从properties配置文件里面读数据

2009-10-27 10:44:00 | By: 访客M62Tl8(游客) ]
 
学习了,呵呵,谢谢
 

个人主页 | 引用 | 返 回 | 删除 | 回复
 
Re:用java从properties配置文件里面读数据

2008-1-14 20:52:00 | By: 张森的测试用户 ]
 
InputStream fis=getClass().getResourceAsStream("/property.properties");--这种方法不行。谢谢了, 我已经搞定了,目前找到两种方法与大家分享一下: 

◎方法1 
FileInputStream fis=new FileInputStream(getServletContext().getRealPath("/WEB-INF/classes/property.properties")); 
◎方法2 
InputStream fis=getServletContext().getResourceAsStream ("/WEBINF/classes/property.properties");/*可以利用Servlet.ServletConfig的 getServletContex()的方法后返回ServletContext的对象,再利用ServletContext的 getResourceAsStream()方法并返回InputStream的对象%>*/ 


将InputStream fis=getClass().getResourceAsStream("property.properties"); 
改为 InputStream fis=getClass().getResourceAsStream(application.getRealPath("/")+"WEB-INF/classesproperty.properties");
 

个人主页 | 引用 | 返 回 | 删除 | 回复
 
 
Re:用java从properties配置文件里面读数据

2007-12-18 20:49:00 | By: 张森的测试用户 ]
 

代码实例 

package configuration;public class Configuration
...{
private Properties propertie;
private FileInputStream inputFile;
private FileOutputStream outputFile;

/** *//**
* 初始化Configuration类
*/
public Configuration()
...{
propertie = new Properties();
}

/** *//**
* 初始化Configuration类
* @param filePath 要读取的配置文件的路径+名称
*/
public Configuration(String filePath)
...{
propertie = new Properties();
try ...{
inputFile = new FileInputStream(filePath);
propertie.load(inputFile);
inputFile.close();
} catch (FileNotFoundException ex) ...{
System.out.println("读取属性文件 --->失败!- 原因:文件路径错误或者文件不存在");
ex.printStackTrace();
} catch (IOException ex) ...{
System.out.println("装载文件--->失败!");
ex.printStackTrace();
}
}//end ReadConfigInfo(...)

以下为张森的测试用户的回复: 
今天写了一个读取配置文件信息的程序如下(演示代码不 可用于工程 ):

java 代码
public class Config { 
private static Properties prop = new Properties(); 
static { 
try { 
//prop.load(Config.class.getResourceAsStream("../../config/config.properties")); 
prop.load(Config.class.getResourceAsStream("../aa/config.properties")); 
} catch (IOException e) { 
System.out.println("文件不存在!"); 
e.printStackTrace(); 


public static String CONNECTION_TYPE = prop.getProperty("conn_type"); 
public static String CONNECTION_URL = prop.getProperty("conn_url"); 
public static String CONNECTION_USER = prop.getProperty("conn_user"); 
public static String CONNECTION_PWD = prop.getProperty("conn_pwd"); 
public static String CONNECTION_DRIVER = prop.getProperty("conn_driver"); 
public static String DB_CFG_URL = prop.getProperty("DB_CFG_URL"); 
public static String DB_CFG_USER = prop.getProperty("DB_CFG_USER"); 
public static String DB_CFG_PASSWORD = prop.getProperty("DB_CFG_PASSWORD"); 



html 代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<!--CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"</sp-->> 
<%@ page import="com.*" %> 
<html> 
<head> 
<title>首页title> 
head> 
<body> 
URL名:<%=Config.DB_CFG_URL%><br> 
用户 名:<%=Config.DB_CFG_USER%><br> 
密 码:<%=Config.DB_CFG_PASSWORD%> 
body> 

配置文件的路径如下:1、 WEB-INF----->config------->config.properties

2、WEB- INF------>classes----->aa----->config.properties

上面的程序可以 读到WEB-INF------>classes----->aa----->config.properties,但读不到WEB- INF----->config------->config.properties

另外一种实现方式:

java 代码
package com; 
import java.io.*; 
import java.util.Properties; 

public class FileConfig 

public Properties getFileProp() 

Properties prop = new Properties(); 
try { 
//File fClass = new File("applications/d
 btest/WEB-INF/config/config.properties"); 
File fClass = new File("webapps/dbtest/WEB-INF/config/config.properties"); 
FileInputStream fis = new FileInputStream(fClass); 
prop.load(fis); 
} catch (IOException e) { 
System.out.println("文件不存在!"); 
e.printStackTrace(); 

if(prop != null) 
return prop; 
else 
return null; 




html代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ page import="com.FileConfig" %> 
<!--CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"</sp-->> 
<html> 
<head> 
<title>首页title> 
head> 
<body> 
<% 
FileConfig fc = new FileConfig(); 
Properties prop = fc.getFileProp(); 
%> 
body> 
<%=prop.getProperty("DB_CFG_PASSWORD")%> 
<%=prop.getProperty("DB_CFG_USER")%> 
<%=prop.getProperty("DB_CFG_URL")%> 

第二种方法解决了不能读取 classes上次目录下文件内容的问题。它认的是容器的根目录如:tomcat就是webapps是第一级录,而在weblogic下则是 applications。

如果您刚刚开始接触网页设计,是不是经常发生这样的问题呢?做好的网页在自己机器上可以正常浏览,而把页面传 到服务器上就总是出现看不到图片,css样式表失效等错误。这种情况下多半是由于你使用了错误的路径,在应该使用相对路径的地方使用了绝对路径,导致浏览 器无法在指定的位置打开指定的文件。 



以下为张森的测试用户的回复: 
今天写了一个读取配置文件信息的程序如下(演示代码不 可用于工程 ):

java 代码
public class Config { 
private static Properties prop = new Properties(); 
static { 
try { 
//prop.load(Config.class.getResourceAsStream("../../config/config.properties")); 
prop.load(Config.class.getResourceAsStream("../aa/config.properties")); 
} catch (IOException e) { 
System.out.println("文件不存在!"); 
e.printStackTrace(); 


public static String CONNECTION_TYPE = prop.getProperty("conn_type"); 
public static String CONNECTION_URL = prop.getProperty("conn_url"); 
public static String CONNECTION_USER = prop.getProperty("conn_user"); 
public static String CONNECTION_PWD = prop.getProperty("conn_pwd"); 
public static String CONNECTION_DRIVER = prop.getProperty("conn_driver"); 
public static String DB_CFG_URL = prop.getProperty("DB_CFG_URL"); 
public static String DB_CFG_USER = prop.getProperty("DB_CFG_USER"); 
public static String DB_CFG_PASSWORD = prop.getProperty("DB_CFG_PASSWORD"); 



html 代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<!--CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"</sp-->> 
<%@ page import="com.*" %> 
<html> 
<head> 
<title>首页title> 
head> 
<body> 
URL名:<%=Config.DB_CFG_URL%><br> 
用户 名:<%=Config.DB_CFG_USER%><br> 
密 码:<%=Config.DB_CFG_PASSWORD%> 
body> 

配置文件的路径如下:1、 WEB-INF----->config------->config.properties

2、WEB- INF------>classes----->aa----->config.properties

上面的程序可以 读到WEB-INF------>classes----->aa----->config.properties,但读不到WEB- INF----->config------->config.properties

另外一种实现方式:

java 代码
package com; 
import java.io.*; 
import java.util.Properties; 

public class FileConfig 

public Properties getFileProp() 

Properties prop = new Properties(); 
try { 
//File fClass = new File("applications/dbtest/WEB-INF/config/config.properties"); 
File fClass = new File("webapps/dbtest/WEB-INF/config/config.properties"); 
FileInputStream fis = new FileInputStream(fClass); 
prop.load(fis); 
} catch (IOException e) { 
System.out.println("文件不存在!"); 
e.printStackTrace(); 

if(prop != null) 
return prop; 
else 
return null; 




html代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<%@ page import="com.FileConfig" %> 
<!--CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"</sp-->> 
<html> 
<head> 
<title>首页title> 
head> 
<body> 
<% 
FileConfig fc = new FileConfig(); 
Properties prop = fc.getFileProp(); 
%> 
body> 
<%=prop.getProperty("DB_CFG_PASSWORD")%> 
<%=prop.getProperty("DB_CFG_USER")%> 
<%=prop.getProperty("DB_CFG_URL")%> 

第二种方法解决了不能读取 classes上次目录下文件内容的问题。它认的是容器的根目录如:tomcat就是webapps是第一级录,而在weblogic下则是 applications。

如果您刚刚开始接触网页设计,是不是经常发生这样的问题呢?做好的网页在自己机器上可以正常浏览,而把页面传 到服务器上就总是出现看不到图片,css样式表失效等错误。这种情况下多半是由于你使用了错误的路径,在应该使用相对路径的地方使用了绝对路径,导致浏览 器无法在指定的位置打开指定的文件。 



以下为张森的测试用户的回复: 
用java从properties配置文件里面读数据 -Servlet
第一步:配置文件
1. web.xml
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>com.0734w.util.InitServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/config.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

2.config.properties
假 若在config.properties配置如下
app1.name=dog
app2.name=pig

3.在 Constants.java中定义
public final static String APP1NAME = "app1.name"; 
public final static String APP2NAME = "app2.name"; 

第二步:定义InitServlet

package com.0734w.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.PropertyResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;


import com.cpic.adapter.adapterapp.constant.Constants;

/**
* <p>Title:InitServlet.java</p>
* <p>Description:当应用起动时加载要读取的数据放入context中</p>
* @author spark 2005-12-26
* @version 1.0
*/
public class InitServlet extends HttpServlet {
private Logger logger;

public void init() throws ServletException{
super.init();
ServletContext context = getServletContext();
context.setAttribute(Constants.ADAPTER_INIT_STATUS,Boolean.FALSE); 
//initialize proxy configuration
initAdapter();
context.setAttribute(Constants.ADAPTER_INIT_STATUS,Boolean.TRUE);
logger.info("initAdapter initialized successfully");
}


/**
* <p>Description:加载和设置数据</p>
* @throws ServletException
* spark 2005-12-26
*/
private void initAdapter() throws ServletException{
ServletContext context = getServletContext();
String configFile = getInitParameter("config");
if (configFile == null) {
String errMsg="Initialize Adapter configuration config file is not set in web.xml.";
logger.error(errMsg);
ServletException e = new ServletException(errMsg);
throw e; 
}

InputStream in;
PropertyResourceBundle configBundle;
try {
in = this.getServletContext().getResourceAsStream(configFile);
configBundle = new PropertyResourceBundle(in);
//需要读取的数据每一个数据都要从这里 定义 context.setAttribute(Constants.APP1NAME,configBundle.getString(Constants.APP1NAME));
context.setAttribute(Constants.APP2NAME,configBundle.getString(Constants..APP2NAME));

} catch (IOException e) {
String errMsg = "Initialize adapter config.properties failed.";
logger.error(errMsg);
ServletException e1 = new ServletException(errMsg);
throw e1; 
}
catch (Exception e) {
String errMsg = "Initialize adapter config.properties failed.";
logger.error(errMsg);
ServletException e1 = new ServletException(errMsg);
throw e1; 
}

}

}

第三 步,在应用利用:<

 br />在servlet中如下:
ServletContext context = getServletContext();
( String) context.getAttribute(Constants.APP1NAME)
在STRUTS的ACTION中如下:
ServletContext context = request.getSession().getServletContext();
(String) context.getAttribute(Constants.APP1NAME);

以下为张森的测试用户的回复: 
使用J2SE API读取Properties文件的六种方法

1。 使用java.util.Properties类的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);

2。使用java.util.ResourceBundle类的 getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

3。使用java.util.PropertyResourceBundle类的构造函数
示 例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);

4。使用class变量的 getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

5。使用class.getClassLoader()所得到的 java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

6。使用java.lang.ClassLoader类的 getSystemResourceAsStream()静态方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);

补充

Servlet中可以使用 javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);

 









  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值