开发者

temp files in memory in java program

开发者 https://www.devze.com 2023-02-11 16:18 出处:网络
Is there a way to force the temporary files created in a java program in memory? Since I use several large xml file, I would have advantages in this way? Should I use a transparent method that allows

Is there a way to force the temporary files created in a java program in memory? Since I use several large xml file, I would have advantages in this way? Should I use a transparent method that allows me to not upset the existing application.

UPDATE: I'm looking at th开发者_Python百科e source code and I noticed that it uses libraries (I can not change) which requires the path of those files ...

Thanks


The only way I can think of is to create a RAM disk and then point the system property java.io.tmpdir to that RAM disk.


XML is just a String, why not just reference Strings in memory, I think the File interface is a distraction. Use StringBuilder if you need to manipulate the data. Use StringBuffer if you need thread safety. Put them in a type safe Map if you have a variable number of things that need to be looked up on with a key.

If you absolutely have to keep the File interface, then create a InMemoryFileWriter that wraps ByteArrayOutputStream and ByteArrayInputStream to keep them in memory, but again I think the whole File in memory thing is a bad decision if you just want to cache things in memory, that is a lot of overhead when a simple String would do.


Don't use files if you don't have to. Consider com.google.common.io.FileBackedOutputStream from Guava:

An OutputStream that starts buffering to a byte array, but switches to file buffering once the data reaches a configurable size.


You probably can force the default behaviour of java.io.File with some reflection magic, but I'm sure you don't want to do that as it can lead to unpredicted behaviour. You're better off providing a mechanism where it would be possible to switch between usual and in-memory behaviour, and route all calls via this mechanism.

Look at this example, it shows how to use file API to create in-memory files.


Assuming you have control over the the streams that are being used to write to the file -

Do you absolutely want the in-memory behavior? If all that you want to do is reduce the number of system calls to write to the disk, you can wrap the FileOutputStream in a BufferedOutputStream (with appropriately big buffer size) and write to this BufferedOutputStream (or BufferedWriter) instead of writing directly to the original FileOutputStream.
(This does require a change in the existing application)

0

精彩评论

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