public class Outer {
public static void main(String args[]) {
try {
FileReader fr = new FileReader("C:\\dirtest\\sample.properties");
Properties pr = new Properties();
pr.load(fr);
pr.forEach((x,y) -> System.out.println(x + ":" + y));
Set s = pr.keySet();
s.forEach(x -> System.out.println(x + ":" + pr.get(x)));
pr.list(System.out);
System.out.println(pr.getProperty("name"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
price:100
name:sato
age:19
price:100
name:sato
age:19
-- listing properties --
price=100
name=sato
age=19
sato
UTF-8指定により日本語全角文字対応
ResourceBundle classで多言語切り替え
CANADA対応のファイルがないのでsample_ja_JP.propertiesが読み込まれている
sample3*.propertiesがないのでMissingResouceException
public class Outer {
public static void main(String args[]) {
try {
FileReader fr = new FileReader("C:\\dirtest\\sample.properties",Charset.forName("UTF-8"));
Properties pr = new Properties();
pr.load(fr);
pr.forEach((x,y) -> System.out.println(x + ":" + y));
Set s = pr.keySet();
s.forEach(x -> System.out.println(x + ":" + pr.get(x)));
pr.list(System.out);
System.out.println(pr.getProperty("name"));
FileInputStream fis = new FileInputStream("C:\\dirtest\\sample.properties");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
Properties pr2 = new Properties();
pr2.load(isr);
pr2.list(System.out);
File f = Paths.get("C:\\dirtest").toFile();
URLClassLoader u = new URLClassLoader(new URL[]{f.toURI().toURL()});
ResourceBundle rb = ResourceBundle.getBundle("sample",Locale.US, u);
System.out.println("---------------");
System.out.println(rb.getString("name"));
ResourceBundle rb2 = ResourceBundle.getBundle("sample",Locale.JAPAN, u);
System.out.println(rb2.getString("name"));
ResourceBundle rb3 = ResourceBundle.getBundle("sample",Locale.CANADA, u);
System.out.println(rb3.getString("name"));
ResourceBundle rb4 = ResourceBundle.getBundle("sample3",Locale.JAPAN, u);
System.out.println(rb4.getString("name"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
sample.properties
name=sato
price=100
address:大阪
age:19
sample_ja_JP.properties
name=佐藤じろう
price=100
address:大阪
age:19
sample_en_US.properties
name=sugar
price=1 dollar
address:Los angeles
age:nineteen
address:大阪
price:100
name:sato
age:19
address:大阪
price:100
name:sato
age:19
-- listing properties --
address=大阪
price=100
name=sato
age=19
sato
-- listing properties --
address=大阪
price=100
name=sato
age=19
---------------
sugar
佐藤じろう
佐藤じろう
Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name sample3, locale ja_JP
at java.base/java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:2055)
at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1689)
at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1593)
at java.base/java.util.ResourceBundle.getBundle(ResourceBundle.java:1284)
at com.mycompany.mavenproject1.Outer.main(Outer.java:47)
Command execution failed.