Java BufferedWriter Write writeFile(String line, File file)

Here you can find the source of writeFile(String line, File file)

Description

write File

License

Apache License

Declaration

public static void writeFile(String line, File file) 

Method Source Code

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

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

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;
import java.io.OutputStreamWriter;

import java.util.Arrays;

import java.util.List;

public class Main {
    public static void writeFile(String line, File file) {
        writeFile(Arrays.asList(new String[] { line }), file);
    }//from   w  w w .  java  2s .  c o  m

    public static void writeFile(String[] lines, File file) {
        writeFile(Arrays.asList(lines), file);
    }

    public static void writeFile(List<String> lines, File file) {
        try {
            File parent = file.getParentFile();
            if ((parent != null) && parent.isDirectory() && !parent.exists()) {
                parent.mkdirs();
            }
        } catch (Exception e) {
            throw new RuntimeException("Unxpected exception when trying to create parent folders for file ["
                    + file.getAbsolutePath() + "].");
        }

        try {
            writeFile(lines, new FileOutputStream(file));
        } catch (IOException e) {
            throw new IllegalArgumentException("File [" + file.getAbsolutePath() + "] cant write to file.", e);
        }

    }

    public static void writeFile(List<String> lines, OutputStream stream) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(stream));
            for (String line : lines) {
                bw.write(line + "\n");
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            close(bw);
        }
    }

    public static void close(Closeable closable) {
        try {
            if (closable != null) {
                closable.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related

  1. writeFile(String directory, String content, String fileName, boolean deleteFileBeforeWriting)
  2. WriteFile(String file)
  3. writeFile(String file, List data)
  4. writeFile(String filename, ArrayList entries)
  5. writeFile(String filename, Map map)
  6. writefile(String m, String path)
  7. writeFile(String outputLocation, String fileName, List content)
  8. writeFile(String p_name, String p_encoding, String p_content)
  9. writeFileAppend(String filePath, String content)