Java Temp File Create nio createTempFile(String name, String extension, String[] lines)

Here you can find the source of createTempFile(String name, String extension, String[] lines)

Description

Create a temp file with the specified name, extension and contents.

License

Apache License

Parameter

Parameter Description
name a parameter
extension a parameter
lines content for the file

Exception

Parameter Description
Exception on failure

Return

Path to temp file

Declaration

public static Path createTempFile(String name, String extension, String[] lines) throws Exception 

Method Source Code

//package com.java2s;
/*//from   w  w w.j  a va2s .c  om
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.BufferedWriter;

import java.io.FileOutputStream;

import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    /**
     * Create a temp file with the specified name, extension and contents.
     * @param name
     * @param extension
     * @param lines content for the file
     * @return {@code Path} to temp file
     * @throws Exception on failure
     */
    public static Path createTempFile(String name, String extension, String[] lines) throws Exception {
        Path tmpFile = Files.createTempFile(name, extension);
        tmpFile.toFile().deleteOnExit();

        try (BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(tmpFile.toFile()), StandardCharsets.UTF_8))) {
            for (int i = 0; i < lines.length; i++) {
                bw.write(lines[i]);
                bw.write("\n");
            }
            return tmpFile;
        } catch (Exception e) {
            tmpFile.toFile().delete();
            throw e;
        }
    }
}

Related

  1. createTempFile()
  2. createTempFile(final Object forObject)
  3. createTempFile(final String name)
  4. createTempFile(String contents)
  5. createTempFile(String name)
  6. createTemporaryFile(String extension)
  7. createTemporaryFileFromURL(final URL url)