java - 将文件中的数据读入HashMap的方法
问题描述
我需要写一个方法,从文件中读取数据到HashMap中,key是文件的行号,value是行中的文本。并且只有 HashMap 值,其键是 2 的幂,必须写入另一个文件。
我现在用一首诗创建了一个文件。编写了一种读取文件的方法,该文件在 ArrayList 中打印文本。运行一个循环并获取行号和文本会很方便。但我不太明白下一步该做什么。
public static void main(String[] args) throws IOException {
List<String> fileToRead = FileWriterReader.ourFileReaderToList("HAMLET.txt");
System.out.println(fileToRead);
public static List<String> ourFileReaderToList(String fileToRead) throws FileNotFoundException {
File file = new File(fileToRead);
List<String> poemLines = new ArrayList<String>();
Scanner in = null;
try {
if (file.exists()) {
in = new Scanner(file);
while (in.hasNextLine()) {
poemLines.add(in.nextLine());
}
}
} finally {
if (in != null) {
in.close();
}
}
return poemLines;
}
public static void ourWriterListToFile(String fileToWrite, List<String> listToWrite) throws IOException {
FileWriter fw = new FileWriter(fileToWrite, true);
BufferedWriter bw = null;
try {
bw = new BufferedWriter(fw);
int k = 0;
for (String s : listToWrite) {
if (k == (listToWrite.size() - 1)) {
bw.write(s);
} else {
bw.write(s + "\n");
}
k++;
}
} finally {
bw.close();
fw.close();
}
}
public static void parsedFile(List<String> listFromFile) {
for (String s : listFromFile)
System.out.println(s);
}
}
解决方案
您当然可以使用循环将 ArrayList 转换为 HashMap。由于该ourFileReaderToList
函数创建的 ArrayList 分别按顺序存储每一行,因此可以使用另一个函数从 List 中读取值并计算行号是多少。
例如:
HashMap listToHashMap(List<String> list) {
HashMap<Integer, String> poemmap = new HashMap<Integer, String>(); //Our hashmap
int linenumber = 0; //Variable to keep track of the line number
for (String line : list) {
poemmap.put(linenumber, line); //Add line and line number to map
linenumber++; //Increment line number
}
return poemmap;
}
此函数将从 List 中生成一个 HashMap 并返回它。get()
当需要写入文件时,可以使用 HashMap 函数检索这些行。
推荐阅读
- javascript - 使用 Extjs3 在组合框中动态加载 json 数据
- python - SQL Alchemy:选择查询中的“u”是什么
- java - 创建一个显示对象数组中的 getter 的类
- sql - 如果今年的数据不可用,如何上传上一年的数据
- mysql - 根据时间间隔查询获取计数值
- rest - Microsoft Graph API - 获取组所有者详细信息以及 azure 中的组详细信息
- flutter - 具有动态容器高度的 TabBarView
- episerver - 从页面上的内容区域中删除块(使用内容区域上的“删除”)以及当用户单击“移至垃圾箱”时触发事件
- php - 如何在页面上提交另一个表单时保留搜索表单结果?
- appium-android - 如何在 AWS 设备场中截取屏幕截图以使用 appium python 运行?