How to add to a DataOutputStream in Java?

I want my program to save the URLs, one at a time, to a file. These addresses must be saved in UTF format to make sure they are correct.

My problem is that the file is being overwritten all the time, and not attached:

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 is NOT added, so how do I add it?

+6
source share
3 answers

The problem turned out to be that I forgot that I put "filen.delete ();" somewhere else.

This is why you (I) should take breaks during encoding: p

0
source

In fact, you should not keep the stream open and write at each iteration. Why don't you just create a line containing 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 this helps.

+1
source

You can achieve this without a DataOutputStream. Here's a simplified example using only FileOutputStream:

 String filen = "C:/testfile.txt"; FileOutputStream FOS = new FileOutputStream(filen , true); FOS.write(("String" + "\r\n").getBytes("UTF-8")); FOS.close(); 

It will just write "String" every time, but you should get this idea.

0
source

Source: https://habr.com/ru/post/987058/


All Articles