gpt4 book ai didi

java - 有效地存储和查询字符串列表

转载 作者:太空宇宙 更新时间:2023-11-04 09:16:32 24 4
gpt4 key购买 nike

我有这样的东西:

  • 类别 1:foo、bar、...
  • 类别 2:baz、qux、...
  • ...

在我的代码中的某个时刻,我必须尽快检索项目属于哪个类别(例如:从“foo”中找到“category1”)。

我必须决定如何以允许我尽快识别类别的方式存储这些列表(我可以自由选择我想要的任何数据结构)。

它不会经常发生,但我还必须能够在之后更新此列表(直接编辑文件或使用 shell 脚本或其他任何东西,这将独立于当前的可执行文件)。

为了将这些列表存储在外部文件中,什么最适合我的需要?

最佳答案

使用 java.util.Properties 可以轻松地在文件中存储 map ,其中项目作为键,类别作为属性。

java.util.Propertiesjava.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"));

如果您运行代码,它将打印出:

cat1
cat2

如果您编辑创建的 index.properties 文件,这就是您所看到的:

#index
#Mon Oct 30 15:41:35 GMT 2017
fooz=cat2
foo=cat1
baz=cat2
ba=cat1

关于java - 有效地存储和查询字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47017632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com