how to create new java.io.File in memory? [closed]

2019-01-17 13:55发布

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 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 digest of 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 temporary file would be appreciated.

I think now this question is not offtopic

3条回答
混吃等死
2楼-- · 2019-01-17 14:19

You can use a java.io.StringWriter.

查看更多
做自己的国王
3楼-- · 2019-01-17 14:21

To write to a stream, in memory, use:

new ByteArrayOutputStream();
查看更多
Lonely孤独者°
4楼-- · 2019-01-17 14:34

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.

查看更多
登录 后发表回答