やりたいこと
XML形式のプロパティが使いたい。
なぜ?
native2asciiのエンコードされた日本語文字列はメンテナンスするのが面倒なので。
環境
JDK1.5以降
説明
とくに難しいことはしていません。storeToXML()とloadFromXML()しているだけです。プロパティから値を取得したい場合はgetProperty(キー)とかしてください。PropertiesのJavaDocとかも参照のこと。
サンプルコード
streamの扱いは適当なんで、BufferedOutputStreamとかBufferedInputStream使ってください。
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.Properties;
-
- public class Application {
-
- private static final String XML_PROPERTIES_NAME = "test";
- private static final String XML_PROPERTIES_NAME_SUFFIX = ".properties.xml";
- private static final String XML_PROPERTIES_FILE_NAME = XML_PROPERTIES_NAME + XML_PROPERTIES_NAME_SUFFIX;
- private static final String XML_COMMENT = "プロパティのコメント";
-
- private Properties getProperties() {
- Properties properties = new Properties();
- properties.setProperty("usage", "このプログラムの使用方法");
- properties.setProperty("test", "テスト文字列");
-
- return properties;
- }
-
- private void saveProp() throws IOException {
- Properties properties = getProperties();
-
- OutputStream stream = new FileOutputStream(XML_PROPERTIES_FILE_NAME);
- properties.storeToXML(stream, XML_COMMENT);
-
- stream.close();
- }
-
- private void loadProp() throws IOException {
- InputStream stream = new FileInputStream("test.properties.xml");
-
- Properties prop = new Properties();
- prop.loadFromXML(stream);
-
- stream.close();
-
- prop.list(System.out);
- }
-
-
-
-
-
- public static void main(String[] args) throws IOException {
- Application app = new Application();
- app.saveProp();
- app.loadProp();
- }
- }
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class Application {
private static final String XML_PROPERTIES_NAME = "test";
private static final String XML_PROPERTIES_NAME_SUFFIX = ".properties.xml";
private static final String XML_PROPERTIES_FILE_NAME = XML_PROPERTIES_NAME + XML_PROPERTIES_NAME_SUFFIX;
private static final String XML_COMMENT = "プロパティのコメント";
private Properties getProperties() {
Properties properties = new Properties();
properties.setProperty("usage", "このプログラムの使用方法");
properties.setProperty("test", "テスト文字列");
return properties;
}
private void saveProp() throws IOException {
Properties properties = getProperties();
OutputStream stream = new FileOutputStream(XML_PROPERTIES_FILE_NAME);
properties.storeToXML(stream, XML_COMMENT);
stream.close();
}
private void loadProp() throws IOException {
InputStream stream = new FileInputStream("test.properties.xml");
Properties prop = new Properties();
prop.loadFromXML(stream);
stream.close();
prop.list(System.out);
}
/**
* @param args the command line arguments
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Application app = new Application();
app.saveProp();
app.loadProp();
}
}