2012-03-16 94 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(); 
    } 
} 
相关问题