Skip to content

Instantly share code, notes, and snippets.

@tomoTaka01
Last active August 29, 2015 14:01
Show Gist options
  • Save tomoTaka01/73fd0df702d9cb929f43 to your computer and use it in GitHub Desktop.
Save tomoTaka01/73fd0df702d9cb929f43 to your computer and use it in GitHub Desktop.
Creating properties file (package java.util.Propertiesを参考に作成、keyでソート、¥nはそのまま出力)
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* creating properties file sample
*
* @author tomo
*/
public class PropertiesSample {
/**
* creating properties file sample
*
* @param args the command line arguments
*/
public static void main(String... args) {
Map<String, String> map = getKeyValMap();
Path path;
if (args.length > 1){
path = Paths.get(args[0]);
} else {
path = Paths.get("/Users", "tomo", "sample.properties");
}
createProp(map, path);
}
private static Map<String, String> getKeyValMap() {
Map<String, String> map = new TreeMap<>(); // <-- sort
map.put("key1", "val1");
map.put("key2", "val2あ"); // \u3042
map.put("key3", "val3𩸽"); // \uD867\uDE3D
map.put("key4", "val4¥n");
map.put("key5", "val5ア"); // \u30A2
return map;
}
private static void createProp(Map<String, String> map, Path path) {
try (BufferedWriter writer = Files.newBufferedWriter(path, Charset.forName("ISO-8859-1"));) {
for (String key : map.keySet()) {
String line = key + "=" + toHex(map.get(key));
writer.write(line);
writer.newLine();
}
} catch (IOException ex) {
Logger.getLogger(PropertiesSample.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static String toHex(String val) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < val.length(); i++) {
char c = val.charAt(i);
if (!isEacapeTarget(c)){
sb.append(c);
} else {
sb.append("\\u");
sb.append(hexDigit[((c >> 12) & 0xF)]);
sb.append(hexDigit[((c >> 8) & 0xF)]);
sb.append(hexDigit[((c >> 4) & 0xF)]);
sb.append(hexDigit[(c & 0xF)]);
}
}
return sb.toString();
}
private static boolean isEacapeTarget(char c) {
if (String.valueOf(c).equals("¥")){
return false;
}
if (c < 128){
return false;
}
return true;
}
private static final char[] hexDigit = {
'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment