Java File Append appendFile(File targetFile, String toWrite)

Here you can find the source of appendFile(File targetFile, String toWrite)

Description

Opens a file (targetFile) and appends a String (toWrite) to it

License

Apache License

Declaration

public static void appendFile(File targetFile, String toWrite) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    /**//from ww  w .  j a  va  2s  . co  m
     * Opens a file (targetFile) and appends a String (toWrite) to it
     */
    public static void appendFile(File targetFile, String toWrite) throws Exception {
        if (!targetFile.exists()) {
            if (!targetFile.createNewFile())
                throw new Exception("File was not created!");
        }
        if (!targetFile.canWrite())
            throw new Exception("No permission to write file!");
        else {
            try {
                // WE CAN WRITE TO THE FILE
                FileWriter fw = new FileWriter(targetFile, true);
                fw.write(toWrite);
                fw.close();
            } catch (Exception e) {
                throw e;
            }
        }
    }

    /**
     * Appends a String to a given file
     *
     * @param fileName The absolute path to the file to be written
     * @param toWrite  The String to write to the file
     */
    public static final void appendFile(String fileName, String toWrite) throws Exception {
        appendFile(new File(fileName), toWrite);
    }
}

Related

  1. appendFile(File file, String content)
  2. appendFile(File file, String url)
  3. appendFile(File filename, String data)
  4. appendFile(File src, File dst)
  5. appendFile(File targetFile, String text)
  6. appendFile(final File srcFile, final File destFile)
  7. appendFile(final String filename, final String content)
  8. appendFile(final String name, final String s)
  9. appendFile(OutputStream output, File source)