Java 读取txt文件到hashmap,用“:”分割
Java read txt file to hashmap, split by ":"
我有一个 txt 文件,格式为:
Key:value
Key:value
Key:value
...
我想将所有键及其值放入我创建的 hashMap 中。如何获得 FileReader(file)
或 Scanner(file)
以了解何时拆分冒号 (:) 处的键和值? :-)
我试过:
Scanner scanner = new scanner(file).useDelimiter(":");
HashMap<String, String> map = new Hashmap<>();
while(scanner.hasNext()){
map.put(scanner.next(), scanner.next());
}
使用 BufferedReader
逐行读取您的文件,并在每一行中第一次出现 :
时执行 split
(如果有没有 :
然后我们忽略那行)。
这是一些示例代码 - 它避免了使用 Scanner(它有一些微妙的行为,恕我直言,实际上麻烦多于它的价值)。
public static void main( String[] args ) throws IOException
{
String filePath = "test.txt";
HashMap<String, String> map = new HashMap<String, String>();
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(":", 2);
if (parts.length >= 2)
{
String key = parts[0];
String value = parts[1];
map.put(key, value);
} else {
System.out.println("ignoring line: " + line);
}
}
for (String key : map.keySet())
{
System.out.println(key + ":" + map.get(key));
}
reader.close();
}
以下将适用于 java 8.
.filter(s -> s.matches("^\w+:\w+$"))
意味着它只尝试在文件中的行上工作,这两个字符串由 :
分隔,显然摆弄这个正则表达式将改变它允许通过的内容。
.collect(Collectors.toMap(k -> k.split(":")[0], v -> v.split(":")[1]))
将处理与前一个过滤器匹配的任何行,在 :
上拆分它们,然后使用该拆分的第一部分作为映射条目中的键,然后使用第二部分该拆分作为映射条目中的值。
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.stream.Collectors;
public class Foo {
public static void main(String[] args) throws IOException {
String filePath = "src/main/resources/somefile.txt";
Path path = FileSystems.getDefault().getPath(filePath);
Map<String, String> mapFromFile = Files.lines(path)
.filter(s -> s.matches("^\w+:\w+"))
.collect(Collectors.toMap(k -> k.split(":")[0], v -> v.split(":")[1]));
}
}
还有一个 JDK 1.8 实现。
我建议使用 try-with-resources 和 forEach
迭代器与 putIfAbsent()
方法来避免 java.lang.IllegalStateException: Duplicate key value 如果有是文件中的一些重复值。
FileToHashMap.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Stream;
public class FileToHashMap {
public static void main(String[] args) throws IOException {
String delimiter = ":";
Map<String, String> map = new HashMap<>();
try(Stream<String> lines = Files.lines(Paths.get("in.txt"))){
lines.filter(line -> line.contains(delimiter)).forEach(
line -> map.putIfAbsent(line.split(delimiter)[0], line.split(delimiter)[1])
);
}
System.out.println(map);
}
}
in.txt
Key1:value 1
Key1:duplicate key
Key2:value 2
Key3:value 3
输出为:
{Key1=value 1, Key2=value 2, Key3=value 3}
我会这样做
Properties properties = new Properties();
properties.load(new FileInputStream(Path of the File));
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
myMap.put((String) entry.getKey(), (String) entry.getValue());
}
我有一个 txt 文件,格式为:
Key:value
Key:value
Key:value
...
我想将所有键及其值放入我创建的 hashMap 中。如何获得 FileReader(file)
或 Scanner(file)
以了解何时拆分冒号 (:) 处的键和值? :-)
我试过:
Scanner scanner = new scanner(file).useDelimiter(":");
HashMap<String, String> map = new Hashmap<>();
while(scanner.hasNext()){
map.put(scanner.next(), scanner.next());
}
使用 BufferedReader
逐行读取您的文件,并在每一行中第一次出现 :
时执行 split
(如果有没有 :
然后我们忽略那行)。
这是一些示例代码 - 它避免了使用 Scanner(它有一些微妙的行为,恕我直言,实际上麻烦多于它的价值)。
public static void main( String[] args ) throws IOException
{
String filePath = "test.txt";
HashMap<String, String> map = new HashMap<String, String>();
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(":", 2);
if (parts.length >= 2)
{
String key = parts[0];
String value = parts[1];
map.put(key, value);
} else {
System.out.println("ignoring line: " + line);
}
}
for (String key : map.keySet())
{
System.out.println(key + ":" + map.get(key));
}
reader.close();
}
以下将适用于 java 8.
.filter(s -> s.matches("^\w+:\w+$"))
意味着它只尝试在文件中的行上工作,这两个字符串由 :
分隔,显然摆弄这个正则表达式将改变它允许通过的内容。
.collect(Collectors.toMap(k -> k.split(":")[0], v -> v.split(":")[1]))
将处理与前一个过滤器匹配的任何行,在 :
上拆分它们,然后使用该拆分的第一部分作为映射条目中的键,然后使用第二部分该拆分作为映射条目中的值。
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.stream.Collectors;
public class Foo {
public static void main(String[] args) throws IOException {
String filePath = "src/main/resources/somefile.txt";
Path path = FileSystems.getDefault().getPath(filePath);
Map<String, String> mapFromFile = Files.lines(path)
.filter(s -> s.matches("^\w+:\w+"))
.collect(Collectors.toMap(k -> k.split(":")[0], v -> v.split(":")[1]));
}
}
还有一个 JDK 1.8 实现。
我建议使用 try-with-resources 和 forEach
迭代器与 putIfAbsent()
方法来避免 java.lang.IllegalStateException: Duplicate key value 如果有是文件中的一些重复值。
FileToHashMap.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Stream;
public class FileToHashMap {
public static void main(String[] args) throws IOException {
String delimiter = ":";
Map<String, String> map = new HashMap<>();
try(Stream<String> lines = Files.lines(Paths.get("in.txt"))){
lines.filter(line -> line.contains(delimiter)).forEach(
line -> map.putIfAbsent(line.split(delimiter)[0], line.split(delimiter)[1])
);
}
System.out.println(map);
}
}
in.txt
Key1:value 1
Key1:duplicate key
Key2:value 2
Key3:value 3
输出为:
{Key1=value 1, Key2=value 2, Key3=value 3}
我会这样做
Properties properties = new Properties();
properties.load(new FileInputStream(Path of the File));
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
myMap.put((String) entry.getKey(), (String) entry.getValue());
}