Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows temporary file in Java

How to create a file in Windows that would have attributes FILE_ATTRIBUTE_TEMPORARY and FILE_FLAG_DELETE_ON_CLOSE set using Java?

I do want my file to be just in-memory file.

To precise: delete-on-exit mechanism does not satisfy me, because I want to avoid situation, when some data is left on disk in case of, for example, application crash.

like image 815
Przemysław Różycki Avatar asked May 25 '10 10:05

Przemysław Różycki


People also ask

What is temporary in Java?

The File class in Java provides a method with name createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix(extension) of the temp file and a File object representing the directory (abstract path) at which you need to create the file.

What is Java IO tmpdir?

io. tmpdir is a standard Java system property which is used by the disk-based storage policies. It determines where the JVM writes temporary files, including those written by these storage policies (see Section 4 and Appendix A. 8). The default value is typically " /tmp " on Unix-like platforms.

What are Windows temporary files?

What are temporary files? Temporary files, also called temp or tmp files, are created by Windows or programs on your computer to hold data while a permanent file is being written or updated. The data will be transferred to a permanent file when the task is complete, or when the program is closed.

How do I know if I have Java IO tmpdir?

The default value is typically "/tmp" , or "/var/tmp" on Unix-like platforms. On Microsoft Windows systems the java. io. tmpdir property is typically "C:\\WINNT\\TEMP" .


2 Answers

Use something like this. It won't be in-memory though, but a temporary file that is deleted when the app exits.

try { 
   // Create temp file. 
   File temp = File.createTempFile("pattern", ".suffix"); 

   // Delete temp file when program exits.
   temp.deleteOnExit();

   // Write to temp file
   BufferedWriter out = new BufferedWriter(new FileWriter(temp));    
   out.write("aString");     
   out.close();
} catch (IOException e) { 
// (..)
} 
like image 194
b.roth Avatar answered Sep 18 '22 22:09

b.roth


Why not just use a memory block i.e. datastructure ? What's the incentive behind creating a file ? If you want a scratch file then temp file and delete on exit will help.

like image 21
whatnick Avatar answered Sep 19 '22 22:09

whatnick