gpt4 book ai didi

java - 使用 Apache Commons VFS 附加到文件

转载 作者:行者123 更新时间:2023-11-30 09:39:40 24 4
gpt4 key购买 nike

如果文件已经存在,我想使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com