我想打印一个数组列表,在该数组列表中它包含哈希映射,并且我在一个文本文件中打印。尝试打印文本文件时,它以单行打印。我需要在另一行 示例:
ArrayList<Object> mainlist= new ArrayList<>();
LinkedHashMap<String, String> hmap = new LinkedHashMap<>();
for (int i=0;i<5;i++)
{
hmap.put("key1", "03-08-2018");
hmap.put("key2", "xyz";
hmap.put("key3", "123");
//ArrayList USed:::
mainlist.add(hmap);
mainlist.add("\n");
}
return mainlist;
我在文本文件中返回。它生成一行,但是我的输出文本文件中需要单独的行。
文本文件中的预期输出:
[{key1=03-08-2018,key2=xyz,key3=123}
{key1=03-08-2018,key2=xyz,key3=123}
{key1=03-08-2018,key2=xyz,key3=123}
]
文本文件中的实际输出:
[{key1=03-08-2018,key2=xyz,key3=123},{key1=03-08-2018,key2=xyz,key3=123},{key1=03-08-2018,key2=xyz,key3=123}]
有人可以帮我解决这个问题吗?
感谢您的答复
答案 0 :(得分:0)
我测试了您的代码,并且对我有用。您如何将其写入文件?
我这样做是这样的:
Path path = Paths.get("/test/outputXXXX.txt");
ArrayList<Object> mainlist= new ArrayList<>();
LinkedHashMap<String, String> hmap = new LinkedHashMap<>();
for (int i=0;i<5;i++)
{
hmap.put("key1", "03-08-2018");
hmap.put("key2", "xyz");
hmap.put("key3", "123");
//ArrayList USed:::
mainlist.add(hmap);
mainlist.add("\n");
}
try (BufferedWriter writer = Files.newBufferedWriter(path))
{
writer.write(mainlist.toString());
}
并在文件中输出:
[{key1=03-08-2018, key2=xyz, key3=123},
, {key1=03-08-2018, key2=xyz, key3=123},
, {key1=03-08-2018, key2=xyz, key3=123},
, {key1=03-08-2018, key2=xyz, key3=123},
, {key1=03-08-2018, key2=xyz, key3=123},
]
编辑: 抱歉,没有逗号就看不到您需要它。
您可以这样做:
Path path = Paths.get("/test/outputXXXX.txt");
ArrayList<Object> mainlist= new ArrayList<>();
LinkedHashMap<String, String> hmap = new LinkedHashMap<>();
for (int i=0;i<5;i++)
{
hmap.put("key1", "03-08-2018");
hmap.put("key2", "xyz");
hmap.put("key3", "123");
//ArrayList USed:::
mainlist.add(hmap);
mainlist.add("\n");
}
try (BufferedWriter writer = Files.newBufferedWriter(path))
{
writer.write("[");
for (Object o : mainlist) {
writer.write(o.toString());
}
writer.write("]");
}
答案 1 :(得分:0)
ArrayList<Object> mainlist= new ArrayList<>();
LinkedHashMap<String, String> hmap = new LinkedHashMap<>();
for (int i=0;i<5;i++)
{
hmap.put("key1", "03-08-2018");
hmap.put("key2", "xyz"); //you missed closing paranthesis here
hmap.put("key3", "123");
//ArrayList USed:::
mainlist.add(hmap);
mainlist.add("\n");
}
return mainlist;
您可以在:: https://www.tutorialspoint.com/compile_java_online.php
中尝试以下代码import java.util.*;
public class ArrayListExample{
public static void main(String args[]){
ArrayList<Object> mainlist= new ArrayList<>();
LinkedHashMap<String, String> hmap = new LinkedHashMap<>();
int i=0;
for (i=0;i<5;i++) {
hmap.put("key1", "03-08-2018");
hmap.put("key2", "xyz");
hmap.put("key3", "123");
//ArrayList USed:::
mainlist.add(hmap);
mainlist.add("\n");
}
System.out.println(mainlist);
return;
}
}
这给出了您的预期输出。希望这对您有所帮助。 谢谢。