java.util.Properties
を使用すると、アイテムをキーとして、カテゴリをプロパティとして持つファイルにマップを簡単に格納することができます。
java.util.Properties
は、java.util.Hashtable
の拡張子であり、java.util.HashMap
に非常に似ています。あなたは、コードを実行した場合
Properties properties = new Properties();
properties.setProperty("foo", "cat1");
properties.setProperty("ba", "cat1");
properties.setProperty("fooz", "cat2");
properties.setProperty("baz", "cat2");
File storage = new File("index.properties");
// write to file
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(storage), "UTF-8"))) {
properties.store(writer, "index");
}
// Read from file
Properties readProps = new Properties();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(storage), "UTF-8"))) {
readProps.load(reader);
}
if(!readProps.equals(properties)) {
throw new IllegalStateException("Written and read properties do not match");
}
System.out.println(readProps.getProperty("foo"));
System.out.println(readProps.getProperty("fooz"));
:ファイルとバックファイルからそれを読むためにプロパティにカテゴリマップ -
つまり、あなたのアイテムをシリアル化するために、以下の例のようなコードを使用することができますそれがプリントアウトされます:あなたが作成したindex.propertiesファイルを編集する場合
cat1
cat2
、これはあなたが見るものである。
#index
#Mon Oct 30 15:41:35 GMT 2017
fooz=cat2
foo=cat1
baz=cat2
ba=cat1
あるカテゴリ内の文字列が他のカテゴリ内に存在しない場合、カテゴリに対する文字列の単純なマップは問題ありません。各リスト内に重複が必要な場合は、リストのカテゴリのマップを使用できます。 firsのソリューションでは、map.get( "foo")はcategory1を返します。 2番目の方法では、マップのキーセットを繰り返して、必要な文字列を含むリストを探し、見つかったときに一致するカテゴリを返します。 –
ファイルに正確にどのように格納されているかは重要ですか? Javaデータ構造の提案を求めるか、ファイルレイアウトを求めるかは明確ではありません。通常、ファイルを読むのは非常に遅いので、どのようにパフォーマンスが向上するかは問題になりません。 – daniu