-1

它工作正常,但我需要逐行写入数据。我从 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

4 回答 4

1

您可以简单地将“\n”附加到您编写的每个字符串,或使用PrintWriter

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

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

于 2013-06-28T11:15:07.033 回答
0

Replace this:

System.out.println("");

with this:

writer.write("\n");
于 2013-06-28T11:15:44.060 回答
0

要逐行编写语句,请在您周围包装一个BuffererdWriterFileWriter并使用newLine()

BufferedWriter bw = new BufferedWriter(new FileWriter(path));
bw.write(str);
bw.newLine();

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

于 2013-06-28T11:18:53.187 回答
0

像这样的东西?

writer.write(str + "\n");
于 2013-06-28T11:14:20.963 回答