How to write data to temporary file in Java?

  • Below example shows how to write or store data into a temporary file in java.
package com.nourit.javaIO;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteDataToTempFileExample {

  public static void main(String[] args) throws IOException {
    File tempFile = null;
    BufferedWriter writer = null;
    try {
      //create a temp file
      tempFile = File.createTempFile("NouritTempFile", ".tmp");
      //write the content
      writer = new BufferedWriter(new FileWriter(tempFile));
      writer.write("Writing data into temp file!!!");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
        if (writer != null){
          writer.close();
        }
    }
    System.out.println("Stored data in temporary file.");
  }
}

Output:

Stored data in temporary 'NouritTempFile' file.

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*