开发者

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, w开发者_开发技巧hen some data is left on disk in case of, for example, application crash.


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) { 
// (..)
} 


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.


Even with both the flags set your files might end up in the filesystem. If the system cache becomes too small, the file is written to the disk, and if the system crashes, no afterprocess cleanup is performed.

However, I like your idea and wonder why the JVM implementation on Windows doesn't use the flags by default. At least deleteOnExit() should be implemented like this as a fallback.


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

Marking a file as temporary and delete-on-close on Windows won't guarantee that it is not written to the file system.

With UNIX / Linux you could create the file in TmpFS or RamFS file system; i.e. a file system that stores files in RAM memory. TmpFS is backed by virtual memory, so some or all of a file in RamFS may end up on the swap disc. RamFS is not backed by virtual memory, and should only ever reside in RAM.

An overview of RamFS and TmpFS can be found here.

Note however that it is possible (at least in theory) for RamFS contents to end up on disc.

  • If the system is put into hibernate state, the entire contents of RAM is saved to disc before the system is powered down.

  • If the kernel can be induced to crash and kernel crash dumps are enabled, the contents of kernel memory (probably including the RamFS) will be written to the dump.


You are after a windows specific solution, so why not create files using wndows commands execed via Processbuilder.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜