我有一个map的数组列表,我需要将每个map的键写入一个由竖线(|)分隔的文件中。下一行中的下一个映射的键,依此类推。我不熟悉文件操作。请帮帮我
编辑-很抱歉没有包括我所做的,我已经做了以下工作,它没有逐行书写,许多空白行之间
if(alPrdt.size()>0)
{
if (!file.exists()) {
System.out.println("no file. creating new file");
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(),true);
bw = new BufferedWriter(fw);
//s.writeObject(alPrdt);
for(int i=0;i<alPrdt.size();i++)
{
String temp = null;
Map map=(Map) alPrdt.get(i);
Iterator it=map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println("pairs:"+pairs.toString());
if(pairs.getValue()==null)
temp = "";
else
temp = pairs.getValue().toString();
bw.write(temp);
bw.write("|");
it.remove();// avoids a ConcurrentModificationException
}
bw.write("\n");
}
bw.close();
}发布于 2013-10-29 21:19:07
如果您只想要此文件中的密钥,则可能:
String pathToFile = "C:\\temp\\file.txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(pathToFile))) {
for (Map<String, String> map : mapList) {
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
bw.write(it.next());
if (it.hasNext()) {
bw.write("|");
}
it.remove();
}
bw.write(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}发布于 2013-10-29 21:27:01
Java7使用java.nio.file.Files将列表转换为文件,其中列表项表示行:
Files.write(Paths.get("C:\\temp\\file.txt"), lines, StandardCharsets.UTF_8);其中lines为List<String>
因此,(我确信)您可以通过提取密钥轻松地将List<Map>转换为List<String>。
希望能对你有所帮助
https://stackoverflow.com/questions/19658889
复制相似问题