使用FileWriter类从arraylist对象写入文本文件

时间:2013-06-28 11:11:05

标签: java swing io

工作正常,但我需要逐行写入数据。我从arraylis对象获取一个数据,并希望将信号行写入文本文件。第二个对象应该在下一行。

public void writeFile() {
    FileWriter writer = null;
    try {
        writer = new FileWriter("E:/AutomationToolWorkplace/AutomationTool/Test/ExpectedOutputHomescreenModule1.txt");
        for (String str : MP_result_set) {
            System.out.println("");
            writer.write(str);
        }
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(Transciever.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(Transciever.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

输出:

{"data":
{"shared":false,
"port":"4096",
"packageName":"",
"installed":false,
"lock":false,
"like":false,
"type":"HomeScreen",
"ip":"192.168.1.24",
"screenId":"9999",
"selected":false,
"category":"",
"servicetype":"",
"price":"",
"subscribe":false,
"event":false,
"subtype":"Recommended",
"predefined":false,
"pricingmodel":"PPC",
"packageSelected":false}}

{"data":{
"port":"4096",
"screenId":"2050",
"result":"failure",
"recordList":[],
"reminderList":[],
"msg":"No record",
"playList":[],
"ip":"192.168.1.24"}}

{"data":{
"port":"4096",
"screenId":"12105",
"result":"success",
"list":["music","Action","Romance","Horror","Comedy","Thriller","Mystery","Drama"],
"type":"genre",
"ip":"192.168.1.24"}}

4 个答案:

答案 0 :(得分:1)

您只需在您编写的每个字符串上添加“\ n”,或使用PrintWriter

  

将对象的格式化表示形式打印到文本输出流。

最简单的解决方案是使用Apache Commons IOUtils和IOUtils.writeLines()方法,它采用集合和编写器。它避免了您自己执行迭代的需要。

答案 1 :(得分:0)

这样的东西?

writer.write(str + "\n");

答案 2 :(得分:0)

替换它:

System.out.println("");

用这个:

writer.write("\n");

答案 3 :(得分:0)

FileWriter周围逐行撰写BuffererdWriter并使用newLine()

撰写语句
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
bw.write(str);
bw.newLine();

如Piovezan所述,您还应删除System.out.println(""),因为它只会在您的标准输出而不是您的文件中打印换行符。