我想使用 Apache Commons VFS 将文本附加到文件(如果文件已存在),并创建一个包含该文本(如果文件不存在)的新文件。
查看 VFS 的 Javadoc,FileContent 类中的 getOutputStream(boolean bAppend) 方法似乎可以完成这项工作,但经过相当广泛的 Google 搜索后,我无法弄清楚如何使用 getOutputStream 将文本附加到文件。
我将与 VFS 一起使用的文件系统是本地文件 (file://) 或 CIFS (smb://)。
使用 VFS 的原因是我正在开发的程序需要能够使用与执行程序的用户不同的特定用户名/密码写入 CIFS 共享,并且我希望能够灵活地写入本地文件系统或共享,因此我不只是使用 JCIFS。
如果有人能指出我正确的方向或提供一段代码,我将非常感激。
最佳答案
以下是使用 Apache Commons 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();
}
}
关于java - 使用 Apache Commons VFS 附加到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9742557/