Java Write String to File writeFile(String filePath, String content, boolean append)

Here you can find the source of writeFile(String filePath, String content, boolean append)

Description

write File

License

Open Source License

Declaration

public static synchronized void writeFile(String filePath, String content, boolean append) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;

import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static synchronized void writeFile(String filePath, String content, boolean append) throws IOException {
        File file = new File(filePath);

        if (createFile(filePath)) {
            BufferedWriter bufferedWriter = null;

            try {
                FileWriter fileWriter = new FileWriter(file, append);
                bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(content);
                bufferedWriter.flush();//from  ww  w.ja  v  a2s .co m
            } finally {
                closeResource(bufferedWriter);
            }
        }
    }

    public static synchronized void writeFile(String filePath, String content) throws IOException {
        writeFile(filePath, content, false);
    }

    public static synchronized boolean createFile(String filePath) throws IOException {
        File file = new File(filePath);
        File folder = file.getParentFile();

        boolean folderCreated = folder.exists() || folder.mkdirs();
        boolean fileCreated = file.exists() || file.createNewFile();

        return folderCreated && fileCreated;
    }

    public static void closeResource(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

Related

  1. writeFile(String filePath, String content)
  2. writeFile(String filePath, String content)
  3. writeFile(String filePath, String content)
  4. writeFile(String filePath, String content)
  5. WriteFile(String filepath, String content)
  6. writeFile(String filePath, String contents)
  7. writeFile(String filePath, String fileContent)
  8. writeFile(String filePath, String fileData, boolean isAppend)
  9. writeFile(String filePath, String fileName, String[] args)