我正在尝试写一个位于网络服务器上的文件,所以我正在使用:
URL url1 = new URL("ftp://user:[email protected]/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)位于Connection $ 1.run(Connection.java:113)的java.awt.event.InvocationEvent.dispatch(Unknown Source)at java。 java.awt.EventQueue.access上的awt.EventQueue.dispatchEventImpl(未知来源)$ java(java.awt.EventQueue上的未知来源)java.awt.EventQueue上的$ 3.run(未知来源)$ 3.run(未知来源) Java上的java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(Java)中的.security.AccessController.doPrivileged(Native Method)java.awt.EventDispatchThread.pumpOneEventForFilters(未知来源)java.awt.EventQueue.dispatchEvent(未知来源) java.awt.EventDispatchThread.pumpEventsForFilter(未知源)位于java.awt.EventDispatchThread.pumpEvents(未知源)的java.awt.EventDispatchThread.pumpEventsForHierarchy(未知源)位于java.awt的java.awt.EventDispatchThread.pumpEvents(未知源) .EventDispatchThread.run(未知来源)
第274行是
FileWriter fw = new FileWriter(out,true);
所以我需要更改为String而不是OutputStream
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());
}