如何在不覆盖数据的情况下写入文件?

时间:2019-02-17 02:41:23

标签: java outputstream fileoutputstream

我试图写一个位于网络服务器上的文件,所以我在使用:

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);
} 

此代码将覆盖文本文件中的现有数据。我该如何解决?

我从stackoverflow尝试了许多解决方案。每次遇到相同的错误时,都说我需要将OutputStream更改为String

喜欢这个


 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());
        }

错误

  

线程“ AWT-EventQueue-0”中的异常java.lang.Error:未解决的编译问题:       构造函数FileWriter(OutputStream,boolean)未定义

     

在Connection.initialize(Connection.java:274)在   Connection。(Connection.java:131)在   在以下位置连接$ 1.run(Connection.java:113)   java.awt.event.InvocationEvent.dispatch(来源未知)   java.awt.EventQueue.dispatchEventImpl(未知源)在   java.awt.EventQueue.access $ 500(未知源)   java.awt.EventQueue $ 3.run(未知源)   java.awt.EventQueue $ 3.run(未知源)   java.security.AccessController.doPrivileged(本机方法),位于   java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知   源)位于java.awt.EventQueue.dispatchEvent(未知源)位于   java.awt.EventDispatchThread.pumpOneEventForFilters(未知来源)     在java.awt.EventDispatchThread.pumpEventsForFilter(未知来源)     在java.awt.EventDispatchThread.pumpEventsForHierarchy(未知   源)位于java.awt.EventDispatchThread.pumpEvents(未知源)     在java.awt.EventDispatchThread.pumpEvents(未知来源)   java.awt.EventDispatchThread.run(未知来源)

第274行是

FileWriter fw = new FileWriter(out,true); 

所以我需要更改为String而不是OutputStream

2 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分:0)