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?
By default, FileOutputStream creates new file or overwrite when we try to write into a file. If you want to append with the existing content, then you have to use “append” flag in the FileOutputStream constructor.
The DataOutputStream stream lets you write the primitives to an output source. Following is the constructor to create a DataOutputStream. Once you have DataOutputStream object in hand, then there is a list of helper methods, which can be used to write the stream or to do other operations on the stream.
Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way. Java application generally uses the data output stream to write data that can later be read by a data input stream. Let's see the declaration for java.io.DataOutputStream class:
Once you have DataOutputStream object in hand, then there is a list of helper methods, which can be used to write the stream or to do other operations on the stream. Writes len bytes from the specified byte array starting at point off, to the underlying stream. Writes the current number of bytes written to this data output stream.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With