Java – Create Temp File or Directory | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

Java Create Temp File example

package com.example.java.programming.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author code.factory
 *
 */
public class CreateTempFileExample {
	public static void main(String... args) {
		try {
			Path tempFilePath = Files.createTempFile("test", ".txt");
			System.out.printf("Temp file created at %s%n", tempFilePath);
		} catch (IOException ex) {
			System.out.format("I/O error: %s%n", ex);
		}
	}
}

Java Create Temp Directory example

package com.example.java.programming.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author code.factory
 *
 */
public class CreateTempDirectoryExample {
	public static void main(String... args) {
		try {
			Path tempDirPath = Files.createTempDirectory("tempDir");
			System.out.printf("Temporary folder created at %s%n", tempDirPath);
		} catch (IOException ex) {
			System.out.format("I/O error: %s%n", ex);
		}
	}
}

Leave a comment