FileInputStream/BufferedInputStream。_zh_TW.properties 等變體。
InputStream in = servletContext.getResourceAsStream("/WEB-INF/config.properties");
Properties p = new Properties(); p.load(in);
package com.kindani;
import java.util.*; import java.io.*;
public class JProperties {
public static final int BY_PROPERTIES = 1;
public static final int BY_RESOURCEBUNDLE = 2;
public static final int BY_PROPERTYRESOURCEBUNDLE = 3;
public static final int BY_CLASS = 4;
public static final int BY_CLASSLOADER = 5;
public static final int BY_SYSTEM_CLASSLOADER = 6;
public static Properties loadProperties(String name, int type) throws IOException {
Properties p = new Properties(); InputStream in = null;
try {
switch (type) {
case BY_PROPERTIES:
in = new BufferedInputStream(new FileInputStream(name)); p.load(in); break;
case BY_RESOURCEBUNDLE:
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
p = new ResourceBundleAdapter(rb); break;
case BY_PROPERTYRESOURCEBUNDLE:
in = new BufferedInputStream(new FileInputStream(name));
p = new ResourceBundleAdapter(new PropertyResourceBundle(in)); break;
case BY_CLASS:
in = JProperties.class.getResourceAsStream(name); p.load(in); break;
case BY_CLASSLOADER:
in = JProperties.class.getClassLoader().getResourceAsStream(name); p.load(in); break;
case BY_SYSTEM_CLASSLOADER:
in = ClassLoader.getSystemResourceAsStream(name); p.load(in); break;
}
} finally { if (in != null) in.close(); }
return p;
}
// ResourceBundle -> Properties 適配器
static class ResourceBundleAdapter extends Properties {
ResourceBundleAdapter(ResourceBundle rb) {
for (Enumeration e = rb.getKeys(); e.hasMoreElements(); ) {
String k = e.nextElement(); put(k, rb.getObject(k));
}
}
}
}
FileInputStream (方式 1)。ResourceBundle (方式 2/3)。Class.getResourceAsStream (方式 4)。src/main/resources) → 方式 5 或 6。本文來自編程入門網:原文連結