[英]How to append to DataOutputStream in Java?
I want my program to save URL addresses, one at a time, to a file. 我希望我的程序将URL地址(一次一个)保存到文件中。 These addresses need to be saved in UTF format to ensure they are correct.
这些地址需要以UTF格式保存,以确保它们是正确的。
My problem is that the file is overwritten all the time, instead of appended: 我的问题是文件一直被覆盖,而不是附加:
DataOutputStream DOS = new DataOutputStream(new FileOutputStream(filen, true));
Count = 0;
if (LinkToCheck != null) {
System.out.println(System.currentTimeMillis() + " SaveURL_ToRelatedURLS d "+LinkToCheck.Get_SelfRelationValue()+" vs "+Class_Controller.InterestBorder);
if (LinkToCheck.Get_SelfRelationValue() > Class_Controller.InterestBorder) {
DOS.writeUTF(LinkToCheck.Get_URL().toString() + "\n");
Count++;
}
}
DOS.close();
This code does NOT append, so how do I make it append? 此代码不会附加,所以我该如何追加它?
You actually should not keep the stream open and write on every iteration. 实际上,您不应该保持流打开并在每次迭代时写入。 Why don't you simply create a string that contains all the information and write it at the end?
为什么不简单地创建一个包含所有信息的字符串并在最后写出来?
Example: 例:
DataOutputStream DOS = new DataOutputStream(new FileOutputStream(filen, true));
int count = 0; // variables should be camelcase btw
StringBuilder resultBuilder = new StringBuilder();
if (LinkToCheck != null) {
System.out.println(System.currentTimeMillis() + "SaveURL_ToRelatedURLS d "+LinkToCheck.Get_SelfRelationValue()+" vs "+Class_Controller.InterestBorder);
if (LinkToCheck.Get_SelfRelationValue() > Class_Controller.InterestBorder) {
resultBuilder.append(LinkToCheck.Get_URL().toString()).append("\n");
count++;
}
}
DOS.writeUTF(resultBuilder.toString());
DOS.close();
Hope that helps. 希望有所帮助。
You can achieve this without the DataOutputStream. 您可以在没有DataOutputStream的情况下实现此目的。 Here's a simplified example using just the FileOutputStream:
这是一个仅使用FileOutputStream的简化示例:
String filen = "C:/testfile.txt";
FileOutputStream FOS = new FileOutputStream(filen , true);
FOS.write(("String" + "\r\n").getBytes("UTF-8"));
FOS.close();
This will just write "String" everytime, but you should get the idea. 这只是每次都写“字符串”,但你应该明白这一点。
The problem turned out to be that I had forgot I put "filen.delete();" 问题结果是我忘记了我把“filen.delete();” somewhere else.
别的地方。
This is why you(I) should take breaks while coding :p 这就是为什么你(我)应该在编码时休息:p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.