Here you can find the source of createTempFile(String name, String extension, String[] lines)
Parameter | Description |
---|---|
name | a parameter |
extension | a parameter |
lines | content for the file |
Parameter | Description |
---|---|
Exception | on failure |
public static Path createTempFile(String name, String extension, String[] lines) throws Exception
//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; } } }