[英]Print data from a text file imported into a hash map, ignore characters
I have a text file that contains the following:我有一个包含以下内容的文本文件:
example.txt例子.txt
#ignore
#ignore line
#ignore line again
1234567
8940116
12131415
I want to read in the example.txt file into eclipse and add the data into a hashmap.我想将 example.txt 文件读入 eclipse 并将数据添加到 hashmap 中。 I want the list to be arranged in numerical order and I want it to ignore any comments(any text with #) in the text file.
我希望列表按数字顺序排列,并且我希望它忽略文本文件中的任何注释(任何带有 # 的文本)。 I would like to print the hashmap as follows:
我想打印 hashmap 如下:
output: output:
1234567
8940116
12131415
You don't need a hashmap for storing just Strings.您不需要 hashmap 来仅存储字符串。 Maps are for key value pairs.
映射用于键值对。 If you want to put each line from file into a collection use Lists.
如果要将文件中的每一行放入集合中,请使用 Lists。 ArrayLists, LinkedList maintain insertion order.
ArrayLists、LinkedList 维护插入顺序。 You can use any of them.
你可以使用它们中的任何一个。 If you want sorted list you can use TreeList.
如果你想要排序列表,你可以使用 TreeList。
BufferedReader reader;
List<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(
"example"));
String line = reader.readLine();
while (line != null) {
if(!line.startsWith("#"){
list.add(line);
}
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Thr purpose of a Map
is to store pairs Key/Value
, for a single collection you may use a List
it's far more efficient, the printing part is you job whatever the type of collection is Map
的目的是存储对Key/Value
,对于单个集合,您可以使用List
效率更高,打印部分是您的工作,无论集合类型是什么
List<String> values = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("filename"))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("#")) {
values.add(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
for (String v : values)
System.out.println(v);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.