Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java 8 create temporary file

farenda 2015-05-28 0

Problem:

How to create a temporary file in Java 8?

Sometimes it’s needed to create a temporary file during tests, verify result, and then delete it at the end. As usual it can be easily done using Java 8 Files API.

Solution:

package com.farenda.solved;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaSolved {

    public static void main(String[] args) throws IOException {
        String filename = createTempFile();
        printContent(filename);
    }

    // Creates a temporary file that will be deleted on JVM exit.
    private static String createTempFile() throws IOException {
        // Since Java 1.7 Files and Path API simplify operations on files
        Path path = Files.createTempFile("sample-file", ".txt");
        File file = path.toFile();
        // writing sample data
        Files.write(path, "Temporary content...".getBytes(StandardCharsets.UTF_8));
        // This tells JVM to delete the file on JVM exit.
        // Useful for temporary files in tests.
        file.deleteOnExit();
        return file.getAbsolutePath();
    }

    private static void printContent(String filename) throws IOException {
        System.out.println("Reading from: " + filename);
        // In Java 8 you can use forEach() method instead of iterating collection.
        // Moreover static methods can be passed as an arguments.
        Files.readAllLines(Paths.get(filename)).forEach(System.out::println);
    }
}

Result:

Running the program gives the following output:

Reading from: /tmp/sample-file9131501422971123075.txt
Temporary content...

As you can see the file has specified prefix sample-file and designated suffix .txt. Now, when you list files in /tmp directory (or %TEMP% in Windows) you can verify that the file has been deleted:

$> ls -l /tmp/sample*
ls: cannot access /tmp/sample*: No such file or directory
Share with the World!
Categories Java Tags java8-files
Previous: Spring Boot REST HATEOAS
Next: Spock Framework basic test

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok