Java BufferedWriter Write writeFileToString(String filePath, String fileContent, String encoding, boolean append)

Here you can find the source of writeFileToString(String filePath, String fileContent, String encoding, boolean append)

Description

write File To String

License

Apache License

Declaration

public static void writeFileToString(String filePath, String fileContent, String encoding, boolean append)
        throws Exception 

Method Source Code


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

import java.io.*;

public class Main {

    public static void writeFileToString(String filePath, String fileContent, String encoding, boolean append)
            throws Exception {
        PrintWriter out = null;/*from   www . j a v a  2 s .  c  o m*/
        try {
            if (filePath == null || fileContent == null || fileContent.length() <= 0) {
                return;
            }

            File tempFile = new File(filePath);
            if (!tempFile.exists()) {
                tempFile.getParentFile().mkdirs();
                tempFile.createNewFile();
            }

            if (encoding == null || encoding.trim().length() <= 0) {
                out = new PrintWriter(new FileWriter(filePath));
            } else {
                out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(filePath, append), encoding)), true);
            }
            out.print(fileContent);
            out.close();
        } catch (Exception e) {
            throw e;
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static void createNewFile(File f) throws IOException {
        if (f.exists()) {
            f.delete();
        }
        f.getParentFile().mkdirs();
        f.createNewFile();
    }
}

Related

  1. writeFileAppend(String filePath, String content)
  2. writeFileContent(File audioFile, short[] data, boolean littleEndian)
  3. writeFileContents(File file, String contents)
  4. writeFilenames(String folderPath, LinkedList listOfPopulationFiles)
  5. writeFileText(File file, String text)