2012-03-16 93 views
2

如果文件已經存在,我想使用Apache Commons VFS將文本附加到文件,並在文件不存在的情況下創建包含文本的新文件。使用Apache Commons VFS追加到文件

縱觀Javadoc文檔VFS似乎在FileContent類的getOutputStream(布爾bAppend)方法將做的工作,但一個相當廣泛的谷歌搜索後,我無法弄清楚如何使用的getOutputStream將文本追加到一個文件中。

我將與VFS一起使用的文件系統是本地文件(file://)或CIFS(smb://)。

使用VFS的原因是我正在處理的程序需要能夠使用與執行程序的用戶不同的特定用戶名/密碼寫入CIFS共享,我希望能夠靈活地寫入本地文件系統或共享,爲什麼我不只是使用JCIFS。

如果任何人都可以指向正確的方向或提供一段代碼,我將非常感激。

回答

1

我對VFS並不熟悉,但可以用PrintWriter包裝一個OutputStream,並用它來追加文本。

PrintWriter pw = new PrintWriter(outputStream); 
pw.append("Hello, World"); 
pw.flush(); 
pw.close(); 

請注意,PrintWriter使用默認字符編碼。

1

這裏是你如何與Apache下議院VFS做到這一點:

FileSystemManager fsManager; 
PrintWriter pw = null; 
OutputStream out = null; 

try { 
    fsManager = VFS.getManager(); 
    if (fsManager != null) { 

     FileObject fileObj = fsManager.resolveFile("file://C:/folder/abc.txt"); 

     // if the file does not exist, this method creates it, and the parent folder, if necessary 
     // if the file does exist, it appends whatever is written to the output stream 
     out = fileObj.getContent().getOutputStream(true); 

     pw = new PrintWriter(out); 
     pw.write("Append this string."); 
     pw.flush(); 

     if (fileObj != null) { 
      fileObj.close(); 
     } 
     ((DefaultFileSystemManager) fsManager).close(); 
    } 

} catch (FileSystemException e) { 
    e.printStackTrace(); 
} finally { 
    if (pw != null) { 
     pw.close(); 
    } 
} 
相關問題