gpt4 book ai didi

java - 从单个文本文件加载大量属性文件并插入 LinkedHashMap

转载 作者:行者123 更新时间:2023-12-01 15:40:04 25 4
gpt4 key购买 nike

我有一个文件,其中逐行包含大量属性文件,可能大约有 1000 个,每个属性文件将具有大约 5000 个键值对。例如:- 示例示例(abc.txt)-

abc1.properties
abc2.properties
abc3.properties
abc4.properties
abc5.properties

所以我打开这个文件,当它读取每一行时,我在 loadProperties 方法中加载属性文件。并将该属性中的键值对存储在 LinkedHashMap 中。

public class Project {
public static HashMap<String, String> hashMap;

public static void main(String[] args) {
BufferedReader br = null;
hashMap = new LinkedHashMap<String, String>();
try {
br = new BufferedReader(new FileReader("C:\\apps\\apache\\tomcat7\\webapps\\examples\\WEB-INF\\classes\\abc.txt"));
String line = null;
while ((line = br.readLine()) != null) {
loadProperties(line);//loads abc1.properties first time
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//I am loading each property file in this method. And checking whether the key
already exists in the hashMap if it exists in the hashMap then concatenate the
new key value with the previous key value. And keep on doing everytime you
find key exists.

private static void loadProperties(String line) {
Properties prop = new Properties();
InputStream in = Project.class.getResourceAsStream(line);
String value = null;
try {
prop.load(in);
for(Object str: prop.keySet()) {
if(hashMap.containsKey(str.toString())) {
StringBuilder sb = new StringBuilder().append(hashMap.get(str)).append("-").append(prop.getProperty((String) str));
hashMap.put(str.toString(), sb.toString());
} else {
value = prop.getProperty((String) str);
hashMap.put(str.toString(), value);
System.out.println(str+" - "+value);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

}

所以我的问题是,我有超过 1000 个属性文件,每个属性文件有超过 5000 个键值对。大多数属性文件具有相同的键但具有不同的值,因此如果键相同,我必须将该值与前一个值连接起来。那么,随着属性文件的不断增加以及属性文件中的键值对的增加,LinkedHashMap 的大小是否有任何限制。那么这段代码是否经过优化足以处理此类问题?

最佳答案

除了为 JVM 分配的内存堆大小之外,Map 没有任何限制,并且可以使用选项 -Xmx 进行控制

从性能角度来看,您的代码没有问题。

但我可以建议以下改进。

  1. 避免先使用hashMap.containsKey(str.toString()),然后再使用hashMap.get(str)containsKey(key) 实现为 return get(key) != null,因此您实际上调用了 get() 两次。您可以这样说:

    值=map.get(key);如果(值!= null){ 值+=str;}map.put(键, 值);

  2. 不要调用str.toString()。此调用只是创建另一个与原始实例相同的 String 实例。由于 Properties 类未参数化,请使用强制转换,即 (String)str

  3. 如果您仍然遇到性能问题,您可以先合并所有属性文件,然后使用 Properties.load() 一次加载它们。也许您会获得一些性能优势。

关于java - 从单个文本文件加载大量属性文件并插入 LinkedHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8208441/

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