Reputation: 752
I want my program to save URL addresses, one at a time, to a file. These addresses need to be saved in UTF format to ensure they are correct.
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?
Upvotes: 6
Views: 4443
Reputation: 752
The problem turned out to be that I had forgot I put "filen.delete();" somewhere else.
This is why you(I) should take breaks while coding :p
Upvotes: 0
Reputation: 537
You can achieve this without the DataOutputStream. Here's a simplified example using just the 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.
Upvotes: 0
Reputation: 1862
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.
Upvotes: 1