我有一个包含对象的列表(其构造函数包含另一个内部对象)。当我尝试将列表打印到文件时,我会遍历每个对象并调用对象的相应编写器方法。
public void writer(String file, boolean append) {
File path = new File("../Opdracht6_2/src/" + file);
try {
PrintWriter write = new PrintWriter(new FileOutputStream(path,
append));
for (SuperObject o : this.list) {
if (o instanceof Object1) {
((subObject1) w).writer1(file);
}
if (o instanceof Object2) {
((subObject3) w).writer2(file);
}if (o instanceof Object3) {
((subObject3) w).writer3(file);
}
}
write.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
在对象的writer方法中,我尝试先打印一行,说明它是什么类型,然后调用innerobject的writer方法。之后,我希望打印当前对象的参数,然后返回列表编写器方法
public void writer1(String file) {
File path = new File("../Opdracht6_2/src/" + file);
try {
PrintWriter write = new PrintWriter(
new FileOutputStream(path, true));
//below is the string I want to print before the innerobject appends
//its own arguments to the file
write.append("String\r\n");
this.innerobject.innerwriter();
write.append(this objects arg);
write.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
innerobject的作家
public void innerwriter(String file) {
File path = new File("../Opdracht6_2/src/" + file);
try {
PrintWriter write = new PrintWriter(
new FileOutputStream(path, true));
write.append(this objects arg);
write.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
现在实际发生的事情是,我试图首先追加的行会在innerobject的参数之后附加,即使我已经将它放在调用innerobject的writer的方法之前。 它看起来像是在文件中:
内部对象arg
的字符串
外部对象arg
有人可以解释原因吗?
答案 0 :(得分:2)
最好不要在每种方法中使用Writer
。使用单个StringBuilder
附加内容并将其传递给方法。可能是Writer
没有按照附加内容的顺序正确刷新内容。具体来说,write.close()
内的语句innerwriter
将在调用方法中"String\r\n"
实际写入Writer
之前刷新内部对象的内容。
您可以避免创建多个Writer
并改为使用StringBuilder
:
// pass a StringBuilder to append
public void innerwriter(StringBuilder sb) {
sb.append(this objects arg);
}
当您完成附加所有内容后,请使用仅创建一次的Writer
进行撰写:
PrintWriter write = new PrintWriter(new FileOutputStream(path,
append));
StringBuilder sb = new StringBuilder();
for (SuperObject o : this.list) {
if (o instanceof Object1) {
((subObject1) w).writer1(sb);
}
if (o instanceof Object2) {
((subObject3) w).writer2(sb);
} if (o instanceof Object3) {
((subObject3) w).writer3(sb);
}
}
write.append(sb.toString());
write.close();