java file closed_How to create a new java.io.File in memory? [closed]

问题

How can I create new File (from java.io) in memory, not on the hard disk?

I am using the Java language. I don't want to save the file on the hard drive.

I'm faced with a bad API (java.util.jar.JarFile). It's expecting File file of String filename. I have no file (only byte[] content) and can create temporary file, but it's not beautiful solution. I need to validate the digest of a signed jar.

byte[] content = getContent();

File tempFile = File.createTempFile("tmp", ".tmp");

FileOutputStream fos = new FileOutputStream(tempFile);

fos.write(archiveContent);

JarFile jarFile = new JarFile(tempFile);

Manifest manifest = jarFile.getManifest();

Any examples of how to achieve getting manifest without creating a temporary file would be appreciated.

回答1:

To write to a stream, in memory, use:

new ByteArrayOutputStream();

回答2:

How can I create new File (from java.io) in memory , not in the hard disk?

Maybe you are confusing File and Stream:

A File is an abstract representation of file and directory pathnames. Using a File object, you can access the file metadata in a file system, and perform some operations on files on this filesystem, like delete or create the file. But the File class does not provide methods to read and write the file contents.

To read and write from a file, you are using a Stream object, like FileInputStream or FileOutputStream. These streams can be created from a File object and then be used to read from and write to the file.

You can create a stream based on a byte buffer which resides in memory, by using a ByteArrayInputStream and a ByteArrayOutputStream to read from and write to a byte buffer in a similar way you read and write from a file. The byte array contains the "File's" content. You do not need a File object then.

Both the File... and the ByteArray... streams inherit from java.io.OutputStream and java.io.InputStream, respectively, so that you can use the common superclass to hide whether you are reading from a file or from a byte array.

来源:https://stackoverflow.com/questions/17595091/how-to-create-a-new-java-io-file-in-memory

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值