Java Temp File Write writeStringToTempFile(String contents, String path, String encoding)

Here you can find the source of writeStringToTempFile(String contents, String path, String encoding)

Description

Writes a string to a temporary file

License

Open Source License

Parameter

Parameter Description
contents The string to write
path The file path
encoding The encoding to encode in

Exception

Parameter Description
IOException In case of failure

Declaration

public static File writeStringToTempFile(String contents, String path, String encoding) throws IOException 

Method Source Code


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

import java.io.*;

import java.util.zip.GZIPOutputStream;

public class Main {
    /**/*from ww  w .  j a  v  a2  s  . c  o m*/
     * Writes a string to a temporary file
     *
     * @param contents The string to write
     * @param path The file path
     * @param encoding The encoding to encode in
     * @throws IOException In case of failure
     */
    public static File writeStringToTempFile(String contents, String path, String encoding) throws IOException {
        OutputStream writer = null;
        File tmp = File.createTempFile(path, ".tmp");
        if (path.endsWith(".gz")) {
            writer = new GZIPOutputStream(new FileOutputStream(tmp));
        } else {
            writer = new BufferedOutputStream(new FileOutputStream(tmp));
        }
        writer.write(contents.getBytes(encoding));
        return tmp;
    }

    /**
     * Writes a string to a temporary file, as UTF-8
     *
     * @param contents The string to write
     * @param path The file path
     * @throws IOException In case of failure
     */
    public static void writeStringToTempFile(String contents, String path) throws IOException {
        writeStringToTempFile(contents, path, "UTF-8");
    }
}

Related

  1. writeStringToTempFileNoExceptions(String contents, String path)