Java Text File Write nio writeLines(File file, Iterable lines)

Here you can find the source of writeLines(File file, Iterable lines)

Description

Writes lines to a file using UTF-8, overwriting its current contents if it has any.

License

LGPL

Parameter

Parameter Description
file The file
lines The lines

Exception

Parameter Description
IOException In case of an I/O error

Declaration

public static void writeLines(File file, Iterable<String> lines) throws IOException 

Method Source Code

//package com.java2s;
/**/*from  ww  w  .jav  a  2  s.  co  m*/
 * Copyright 2011-2016 Three Crickets LLC.
 * <p>
 * The contents of this file are subject to the terms of the LGPL version 3.0:
 * http://www.gnu.org/copyleft/lesser.html
 * <p>
 * Alternatively, you can obtain a royalty free commercial license with less
 * limitations, transferable or non-transferable, directly from Three Crickets
 * at http://threecrickets.com/
 */

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

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.OutputStreamWriter;

import java.nio.charset.StandardCharsets;

public class Main {
    private static final int BUFFER_SIZE = 16 * 1024;

    /**
     * Writes lines to a file using UTF-8, overwriting its current contents if
     * it has any.
     * <p>
     * Lines end in a newline character.
     * 
     * @param file
     *        The file
     * @param lines
     *        The lines
     * @throws IOException
     *         In case of an I/O error
     */
    public static void writeLines(File file, Iterable<String> lines) throws IOException {
        // Possible bug?
        // See:
        // http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html

        FileOutputStream stream = new FileOutputStream(file);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8),
                BUFFER_SIZE);
        try {
            for (String line : lines) {
                writer.write(line);
                writer.write('\n');
            }
        } catch (IOException x) {
            throw x;
        } finally {
            try {
                stream.close();
            } catch (IOException x) {
            }
        }
    }
}

Related

  1. writeFileTxt(String fileName, String[] totalFile)
  2. writeHeader(DataOutput data, String header)
  3. writeIfSet(final OutputStream outputStream, final String field, final String value)
  4. writeLine(final CharBuffer line, final CharBuffer output)
  5. writeLines(Collection lines, File file)
  6. writeLines(String fileName, String[] lines)
  7. writeLinesToFile(final File file, final String... lines)
  8. writeString(DataOutput dataOutput, String string)
  9. writeString(DataOutput dOut, String value)