Java Read File Into Byte Array

Java Read File Into Byte Array Average ratng: 3,5/5 6075 reviews

Read file content into byte array using NIO in Java 7 Files.readAllBytes() is best method if you are using java 7. Otherwise you will need any method from other 3. This example shows how to read a file in byte array using Java FileInputStream class. This method should only be used when the file size is less than Integer.MAX_VALUE.

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.File class really represents.

Java Read File Into Byte Array

Give More Feedback

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.File class? Have a look If 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, with the latest NIO.2 functionality too. With NIO.2 you can read it in one line using.

Java Read File Into Byte Array

Similarly you can use to write all bytes in your byte array. UPDATE Since the question is tagged Android, the more conventional way is to wrap the FileInputStream in a BufferedInputStream and then wrap that in a ByteArrayInputStream. That will allow you to read the contents in a byte. Similarly the counterparts to them exist for the OutputStream.