How to create temp file in directory

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

/*
 * Here we will learn to create temporary file in temporary directory with provided prefix and suffix.
 * Temp directory is system level enviornment variable.
 */
public class CreateTempDirInDefaultDir {

	public static void main(String args[]) throws IOException {

		File tempFile = null;
		{

			/*
			 * Creates an empty file in the default temporary-file directory,
			 * using the given prefix and suffix to generate its name.
			 */
			/*
			 * To know the temp folder of SYSTEM we can use GETENV method from
			 * System class as below.
			 */
			String tempLoc = System.getenv("java.io.tmpdir");
			System.out.println("Temp directory is :" + tempLoc);

			if (tempLoc == null) {
				// Here we are setting temp directory ENVIORNMENT VARIABLE
				System.setProperty("java.io.tmpdir", "D:\JBT\testing");
			}

			System.out.println("After setting the temp directory location");
			System.out.println("Temp directory is :"
					+ System.getenv("java.io.tmpdir"));

			/*
			 * Creates an empty file in the default temporary-file directory,
			 * using the given prefix and suffix to generate its name.
			 */
			tempFile = File.createTempFile("tempPre", "tempSuff");
		}

		/*
		 * exists() method tests whether the file or directory denoted by this
		 * abstract pathname exists or not accordingly it will return TRUE /
		 * FALSE.
		 */
		if (tempFile.exists())
			System.out.println("Temp File successfully created");
		else
			System.out.println("Failed to create Temp File");
	}
}

 

By | 2012-09-21T19:35:31+00:00 September 21st, 2012|Code Base|0 Comments

About the Author:

Leave A Comment