2

I would like to use Apache Commons VFS to append text to a file if the file already exists and create a new file containing the text if the file does not exist.

Looking at the Javadoc for VFS it appears that getOutputStream(boolean bAppend) method in the FileContent class will do the job but after a fairly extensive Google search I cannot figure out how to use getOutputStream to append text to a file.

The filesystem I will be using with VFS is either a local file (file://) or CIFS (smb://).

The reason for using VFS is the program I'm working on needs to be able to write to a CIFS share using a specific username/password which is different to the user executing the program and I want the flexibility to write to the local filesystem or a share hence why I'm not just using JCIFS.

If anyone can point me in the right direction or provide a snippet of code I would be very grateful.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Paul H
  • 2,104
  • 7
  • 39
  • 53

2 Answers2

2

Here is how you do it with 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();
    }
}
Voicu
  • 16,921
  • 10
  • 60
  • 69
1

I am not familiar with VFS, but you can wrap an OutputStream with a PrintWriter, and use it to append text.

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

Note that PrintWriter uses the default character encoding.

Patrick
  • 2,102
  • 15
  • 11