【问题标题】:Append to a file using Apache Commons VFS使用 Apache Commons VFS 附加到文件
【发布时间】:2012-04-02 07:24:09
【问题描述】:

如果文件已经存在,我想使用 Apache Commons VFS 将文本附加到文件中,如果文件不存在,我想创建一个包含文本的新文件。

查看 VFS 的 Javadoc 似乎 FileContent 类中的 getOutputStream(boolean bAppend) 方法可以完成这项工作,但经过相当广泛的 Google 搜索后,我无法弄清楚如何使用 getOutputStream 将文本附加到文件。

我将与 VFS 一起使用的文件系统是本地文件 (file://) 或 CIFS (smb://)。

使用 VFS 的原因是我正在处理的程序需要能够使用与执行程序的用户不同的特定用户名/密码写入 CIFS 共享,并且我希望灵活地写入本地文件系统或共享,因此我不只是使用 JCIFS。

如果有人能指出正确的方向或提供代码的 sn-p,我将不胜感激。

【问题讨论】:

    标签: java apache-commons-vfs


    【解决方案1】:

    以下是使用 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();
        }
    }
    

    【讨论】:

      【解决方案2】:

      我不熟悉 VFS,但你可以用 PrintWriter 包装一个 OutputStream,并用它来附加文本。

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

      注意 PrintWriter 使用默认的字符编码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-06
        • 1970-01-01
        • 2017-01-19
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        • 2011-02-27
        相关资源
        最近更新 更多