Propertiesクラスが散らかってるのが気に入らない人のためのクラス
設定ファイル要るな→Propertiesクラス便利→うわ順番めちゃくちゃやん
→作ろう
import java.io.*; import java.util.ArrayList; /** * * @author standstonecraft */ public class MyProperties { private ArrayList<String> keyList; private ArrayList<String> valList; public MyProperties() { } public void load(FileInputStream fis) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(fis)); loadP(br); } public void load(FileInputStream fis, String encoding) throws UnsupportedEncodingException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(fis, encoding)); loadP(br); } private void loadP(BufferedReader br) throws IOException { String s; keyList = new ArrayList<>(); valList = new ArrayList<>(); while ((s = br.readLine()) != null) { if (s.charAt(0) != '/') { String ss[] = s.split("=", 2); keyList.add(ss[0]); valList.add(ss[1]); } } br.close(); } public String getProperty(String key, String value) { int i = keyList.indexOf(key); if (i > -1) { return valList.get(i); } return value; } public void setProperty(String key, String value) { int i = keyList.indexOf(key); if (i > -1) { keyList.remove(i); valList.remove(i); } keyList.add(key); valList.add(value); } public void setComment(String comment) { keyList.add(comment); valList.add(null); } public void store(FileOutputStream fos) throws IOException { String s; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); storeP(bw); } public void store(FileOutputStream fos, String encoding) throws UnsupportedEncodingException, IOException { String s; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, encoding)); storeP(bw); } public void store(FileOutputStream fos, String comment, String encoding) throws UnsupportedEncodingException, IOException { keyList.add(0, comment); valList.add(0, null); String s; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, encoding)); storeP(bw); } private void storeP(BufferedWriter bw) throws IOException { for (int i = 0; i < keyList.size(); i++) { String v=valList.get(i); if (v==null) { bw.write("//"); bw.write(keyList.get(i)); }else{ bw.write(keyList.get(i)+"="+v); } bw.newLine(); } bw.close(); } }
長々と書きました
これを使うと設定ファイルが格納した順になります
すでにPropertiesを使ってる場合Propertiesの頭にMyをつければ使えるようにしたかったのですが、
文字コード指定とかポリモルフィズムの関係で妥協してます
loadやstoreのあたりの引数にご注意ください
他に注意事項としては、
・本家と同じようにキーと値は=で分けること(ファイルを直接いじる場合の注意)
・行区切りにすること
・独自機能としてsetComment(String)すると文頭に//がついたコメントとして格納されること
・コメントはキーと同じように格納した順番、場所に格納されること
・キーはそれぞれ異なる名前でなければならないこと(被ってる場合上にある方が使われます)
・getPropertyで返ってくるのはもちろんString
・XMLのメソッドとかキーリストを出すメソッドはないです
多分動きます
雑魚グラマなので冗長なところとか無駄なところとか要らないところとか間違ってるところとかあると思いますがご愛嬌です