Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert file to byte array and vice versa

Tags:

java

arrays

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); 
like image 277
Reg Avatar asked Nov 12 '12 22:11

Reg


People also ask

How do I write a Bytearray file?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

How do I get bytes from Fileoutputstream?

To convert a file to byte array, ByteArrayOutputStream class is used. This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().

How do I get ByteArrayInputStream from a file?

Use the FileUtils#readFileToByteArray(File) from Apache Commons IO, and then create the ByteArrayInputStream using the ByteArrayInputStream(byte[]) constructor. As noted in my answer, Java 7 already contains a readFileToByteArray in the Files class, no need for an additional library.


2 Answers

Otherwise Try this :

Converting File To Bytes

  import java.io.File;   import java.io.FileInputStream;   import java.io.FileNotFoundException;   import java.io.IOException;      public class Temp {          public static void main(String[] args) {           File file = new File("c:/EventItemBroker.java");           byte[] b = new byte[(int) file.length()];          try {                FileInputStream fileInputStream = new FileInputStream(file);                fileInputStream.read(b);                for (int i = 0; i < b.length; i++) {                            System.out.print((char)b[i]);                 }           } catch (FileNotFoundException e) {                       System.out.println("File Not Found.");                       e.printStackTrace();           }           catch (IOException e1) {                    System.out.println("Error Reading The File.");                     e1.printStackTrace();           }         }     } 

Converting Bytes to File

      public class WriteByteArrayToFile {           public static void main(String[] args) {              String strFilePath = "Your path";             try {                  FileOutputStream fos = new FileOutputStream(strFilePath);                  String strContent = "Write File using Java ";                   fos.write(strContent.getBytes());                  fos.close();            }           catch(FileNotFoundException ex)   {                  System.out.println("FileNotFoundException : " + ex);           }          catch(IOException ioe)  {                  System.out.println("IOException : " + ioe);           }         }      } 
like image 64
RajeshVijayakumar Avatar answered Sep 20 '22 23:09

RajeshVijayakumar


I think you misunderstood what the java.io.File class 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.File class? Have a look here 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 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 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.

like image 29
jbx Avatar answered Sep 21 '22 23:09

jbx