5

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.

4

5 回答 5

4

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) { 
// (..)
} 
于 2010-05-25T10:34:08.860 回答
2

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.

于 2010-05-25T10:36:00.493 回答
1

即使设置了这两个标志,您的文件也可能最终出现在文件系统中。如果系统缓存变得太小,则将文件写入磁盘,如果系统崩溃,则不执行后处理清理。

但是,我喜欢您的想法,并想知道为什么 Windows 上的 JVM 实现默认不使用这些标志。至少 deleteOnExit() 应该像这样作为后备实现。

于 2010-05-25T18:56:48.783 回答
0

您正在寻求特定于 Windows 的解决方案,那么为什么不使用通过 Processbuilder 执行的wndows命令创建文件。

于 2010-05-25T13:20:45.043 回答
0

我确实希望我的文件只是内存文件。

在 Windows 上将文件标记为临时文件并在关闭时删除并不能保证它不会写入文件系统。

使用 UNIX / Linux,您可以在 TmpFS 或 RamFS 文件系统中创建文件;即在 RAM 内存中存储文件的文件系统。TmpFS 由虚拟内存支持,因此 RamFS 中的部分或全部文件可能最终会出现在交换磁盘上。RamFS 不受虚拟内存的支持,并且只能驻留在 RAM 中。

可以在此处找到 RamFS 和 TmpFS 的概述。

但是请注意,RamFS 内容有可能(至少在理论上)最终出现在磁盘上。

  • 如果系统进入休眠状态,则 RAM 的全部内容会在系统断电之前保存到磁盘中。

  • 如果内核可以被诱导崩溃并且内核崩溃转储被启用,内核内存(可能包括 RamFS)的内容将被写入转储。

于 2010-05-25T12:01:54.280 回答