简体   繁体   中英

How to append to DataOutputStream in Java?

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?

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM