Tuesday, March 29, 2016

Java I/O Examples : How To Get Temporary File Path

Intro


This examples will demonstrates how to get or display temporary file path in your operating system (os).

Examples


package com.freesamplecode.java.io;

import java.io.File;
import java.io.IOException;

public class GetTemporaryFilePathDemo {
 public static void main(String[] args){
  try {
   
   //step 1. create a temporary file
   File file = File.createTempFile("tempfile", ".tmp");
   
   //step 2. get absolute path
   String absolutePath = file.getAbsolutePath();
   
   //step 3. get temporary file path
   String temporaryFilePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
   
   //step 4. print to console
   System.out.println("Absolute path : "+absolutePath);
   System.out.println("Temporary File path : "+temporaryFilePath);
   
  } catch (IOException e) {
   System.err.println("Error when creating a file..");
   e.printStackTrace();
  }
  
 }
}

Output


Absolute path : C:\Users\Dev\AppData\Local\Temp\tempfile3944253553416804097.tmp
Temporary File path : C:\Users\Dev\AppData\Local\Temp

Screenshot

How To Get Temporary File Path In Java

0 comments: