I’ve found many ways of converting a file to a byte array and writing byte array to a file on storage.
What I want is to convert java.io.File to a byte array and then convert a byte array back to a java.io.File.
I don’t want to write it out to storage like the following:
//convert array of bytes into file
FileOutputStream fileOuputStream = new FileOutputStream("C:\\testing2.txt");
fileOuputStream.write(bFile);
fileOuputStream.close();
I want to somehow do the following:
File myFile = ConvertfromByteArray(bytes);
I think you misunderstood what the
java.io.Fileclass really represents. It is just a representation of the file on your system, i.e. its name, its path etc.Did you even look at the Javadoc for the
java.io.Fileclass? Have a look hereIf you check the fields it has or the methods or constructor arguments, you immediately get the hint that all it is, is a representation of the URL/path.
Oracle provides quite an extensive tutorial in their Java File I/O tutorial, with the latest NIO.2 functionality too.
With NIO.2 you can read it in one line using java.nio.file.Files.readAllBytes().
Similarly you can use java.nio.file.Files.write() to write all bytes in your byte array.
UPDATE
Since the question is tagged Android, the more conventional way is to wrap the
FileInputStreamin aBufferedInputStreamand then wrap that in aByteArrayInputStream.That will allow you to read the contents in a
byte[]. Similarly the counterparts to them exist for theOutputStream.