Java File Append Text appendText(String out, String text)

Here you can find the source of appendText(String out, String text)

Description

append Text

License

Apache License

Declaration

public static void appendText(String out, String text) 

Method Source Code

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

import java.io.*;

public class Main {
    public static void appendText(String out, String text) {
        try {/*from www  .ja v a 2 s. c om*/
            writeText(new FileWriter(out, true), text);
        } catch (IOException ex) {
            throw new IllegalArgumentException("Cannot append to file " + out);
        }
    }

    public static void appendText(File out, String text) {
        if (out.getParentFile() != null)
            guaranteeDirectory(out.getParentFile());
        try {
            FileWriter outWriter = null;
            if (out.exists())
                outWriter = new FileWriter(out, true);
            else
                outWriter = new FileWriter(out);
            writeText(outWriter, text);
        } catch (IOException ex) {
            throw new IllegalArgumentException(
                    "Cannot append to file " + out.getAbsolutePath() + " because " + ex.getMessage());
        }
    }

    public static void writeText(String out, String text) {
        try {
            writeText(new FileWriter(out), text);
        } catch (IOException ex) {
            throw new IllegalArgumentException("Cannot create file " + out);
        }
    }

    public static void writeText(File out, String text) {
        try {
            writeText(new FileWriter(out), text);
        } catch (IOException ex) {
            throw new IllegalArgumentException("Cannot create file " + out.getAbsolutePath());
        }
    }

    public static void writeText(Writer out, String text) {
        PrintWriter realOut = new PrintWriter(out);
        realOut.print(text);
        realOut.close();
    }

    /**
     * for ce teh creation of directories for the file
     *
     * @param thefile non-null file
     * @throws IllegalArgumentException on failure
     */
    public static void guaranteeDirectory(File thefile) throws IllegalArgumentException {
        if (thefile.exists())
            return;
        File parentFile = thefile.getParentFile();
        if (parentFile == null)
            parentFile = new File(System.getProperty("user.dir"));
        if (parentFile.exists() && parentFile.isDirectory())
            return;
        boolean result = parentFile.mkdirs();
        if (!result)
            throw new IllegalArgumentException("Cannot create directoried for file " + thefile.getAbsolutePath());

    }
}

Related

  1. appendText(File f, String text)
  2. appendText(String path, String text)
  3. appendTextString(File outputFile, String doc)
  4. appendTextToFile(@Nonnull File target, String text)
  5. appendTextToFile(File fileToAppend, Set linesToAppend)