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
You can use a java.io.StringWriter.
To write to a stream, in memory, use:
Maybe you are confusing
File
andStream
:File
is an abstract representation of file and directory pathnames. Using aFile
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 theFile
class does not provide methods to read and write the file contents.Stream
object, likeFileInputStream
orFileOutputStream
. These streams can be created from aFile
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 aByteArrayOutputStream
to read from and write to a byte buffer in a similar way you read and write from a file. Thebyte
array contains the "File's" content. You do not need aFile
object then.Both the
File...
and theByteArray...
streams inherit fromjava.io.OutputStream
andjava.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.