Java File Write nio writeFile(List content, String targetFile)

Here you can find the source of writeFile(List content, String targetFile)

Description

Writes content to targetFile.

License

Apache License

Parameter

Parameter Description
Path targetFile

Exception

Parameter Description
IOException an exception

Declaration

public static void writeFile(List<String> content, String targetFile) throws IOException 

Method Source Code

//package com.java2s;
/**/* ww w. java 2s  .c  o m*/
 * Copyright 2011-2013 BBe Consulting GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.ByteArrayInputStream;
import java.io.File;

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

import java.io.PrintWriter;

import java.util.List;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;

public class Main {
    /**
     * Writes content to targetFile.
     * 
     * @param List<String> content
     * @param Path targetFile
     * @throws IOException
     */
    public static void writeFile(List<String> content, String targetFile) throws IOException {
        final PrintWriter writer = new PrintWriter(new FileWriter(new File(targetFile)));
        try {
            for (String line : content) {
                writer.println(line);
            }
        } finally {
            writer.close();
        }
    }

    /**
     * Writes string to targetFile. Replaces file if it exists or creates a new one if not.
     * 
     * @param String text
     * @param Path targetFile
     * @throws IOException
     */
    public static void writeFile(String text, Path targetFile) throws IOException {
        if (Files.exists(targetFile)) {
            InputStream istream = new ByteArrayInputStream(text.getBytes());
            Files.copy(istream, targetFile, StandardCopyOption.REPLACE_EXISTING);
        } else {
            Path file = Files.createFile(targetFile);
            Files.write(file, text.getBytes(), StandardOpenOption.WRITE);
        }
    }
}

Related

  1. writeFile(File file, String content)
  2. writeFile(File file, String content)
  3. writeFile(File file, String text)
  4. writeFile(FileObject fileObject, String content)
  5. writeFile(OutputStream file, List data)
  6. writeFile(String filename, byte file[])
  7. writeFile(String fileName, String content)
  8. writeFile(String fileName, String content)