How to write to file without overwriting the data?

2019-03-07 04:23发布

问题:

I'm trying to write a file that is located on a webserver, so I'm using:

URL url1 = new URL("ftp://user:pass@ftp.host/public_html/users.txt");
URLConnection conn = url1.openConnection();
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();

try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
    w.write(ipAddress+ hostname);
} 

This code overwrite the existing data in the text file. How I can fix that?

I tried many solutions here, from stackoverflow. Every time I get the same error, saying that I need to change OutputStream to String.

like this one


 try
        {
            FileWriter fw = new FileWriter(out,true); //the true will append the new data
            fw.write("add a line\n");//appends the string to the file
            fw.close();
        }
        catch(IOException ioe)
        {
            System.err.println("IOException: " + ioe.getMessage());
        }

errors

Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: The constructor FileWriter(OutputStream, boolean) is undefined

at Connection.initialize(Connection.java:274) at Connection.(Connection.java:131) at Connection$1.run(Connection.java:113) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

line 274 is

FileWriter fw = new FileWriter(out,true); 

so i need to change out to String instead of OutputStream

回答1:

you need to append to the file

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}


回答2:

Use Writer.append() instead of Writer.write().