38

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);
Ivar
  • 6,138
  • 12
  • 49
  • 61
Reg
  • 741
  • 2
  • 9
  • 24
  • What about using a temporary file? http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String, java.lang.String) – auselen Nov 12 '12 at 23:03

9 Answers9

58

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);
          }

       }
     }
RajeshVijayakumar
  • 10,281
  • 11
  • 57
  • 84
22

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.

jbx
  • 21,365
  • 18
  • 90
  • 144
  • 4
    This would be useful info if the question wasn't tagged Android. The `java.nio.file` package is not part of the Android SDK (which is based on Java 6). – Ted Hopp Nov 13 '12 at 01:28
  • You're right, I didn't notice it was tagged Android, I read the title and the question only. I will add the Java 6 way. – jbx Nov 13 '12 at 14:20
8

Apache FileUtil gives very handy methods to do the conversion

try {
    File file = new File(imagefilePath);
    byte[] byteArray = new byte[file.length()]();
    byteArray = FileUtils.readFileToByteArray(file);  
 }catch(Exception e){
     e.printStackTrace();

 }
Jess
  • 425
  • 1
  • 5
  • 15
  • we can directly pass file as parameter to readFileToByteArray(-) , no need to initialize it with "byte[] byteArray = new byte[file.length()](); ", anyways very useful suggesstion .. thanks – Murli Feb 15 '16 at 11:57
7

You can't do this. A File is just an abstract way to refer to a file in the file system. It doesn't contain any of the file contents itself.

If you're trying to create an in-memory file that can be referred to using a File object, you aren't going to be able to do that, either, as explained in this thread, this thread, and many other places..

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
3

There is no such functionality but you can use a temporary file by File.createTempFile().

File temp = File.createTempFile(prefix, suffix);
// tell system to delete it when vm terminates.
temp.deleteOnExit();
auselen
  • 27,577
  • 7
  • 73
  • 114
  • 1
    On Android, you should use [`Context.getCacheDir`](http://developer.android.com/reference/android/content/Context.html#getCacheDir%28%29) to get the temp file directory and use the 3-arg version of `File.createTempFile()`. That way, if you forget to delete the file, at least it will go away when your app data is cleared or your app is uninstalled. – Ted Hopp Nov 13 '12 at 01:25
3

You cannot do it for File, which is primarily an intelligent file path. Can you refactor your code so that it declares the variables, and passes around arguments, with type OutputStream instead of FileOutputStream? If so, see classes java.io.ByteArrayOutputStream and java.io.ByteArrayInputStream

OutputStream outStream = new ByteArrayOutputStream();
outStream.write(whatever);
outStream.close();
byte[] data = outStream.toByteArray();
InputStream inStream = new ByteArrayInputStream(data);
...
Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
2

1- Traditional way

The traditional conversion way is through using read() method of InputStream as the following:

public static byte[] convertUsingTraditionalWay(File file)
{
    byte[] fileBytes = new byte[(int) file.length()]; 
    try(FileInputStream inputStream = new FileInputStream(file))
    {
        inputStream.read(fileBytes);
    }
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }
    return fileBytes;
}

2- Java NIO

With Java 7, you can do the conversion using Files utility class of nio package:

public static byte[] convertUsingJavaNIO(File file)
{
    byte[] fileBytes = null;
    try
    {
        fileBytes = Files.readAllBytes(file.toPath());
    }
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }
    return fileBytes;
}

3- Apache Commons IO

Besides JDK, you can do the conversion using Apache Commons IO library in 2 ways:

3.1. IOUtils.toByteArray()

public static byte[] convertUsingIOUtils(File file)
{
    byte[] fileBytes = null;
    try(FileInputStream inputStream = new FileInputStream(file))
    {
        fileBytes = IOUtils.toByteArray(inputStream);
    }
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }
    return fileBytes;
}

3.2. FileUtils.readFileToByteArray()

public static byte[] convertUsingFileUtils(File file)
{
    byte[] fileBytes = null;
    try
    {
        fileBytes = FileUtils.readFileToByteArray(file);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return fileBytes;
}
Ilya Budu
  • 119
  • 1
  • 9
0

Server side

@RequestMapping("/download")
public byte[] download() throws Exception {
    File f = new File("C:\\WorkSpace\\Text\\myDoc.txt");
     byte[] byteArray = new byte[(int) f.length()];
        byteArray = FileUtils.readFileToByteArray(f);
        return byteArray;
}

Client side

private ResponseEntity<byte[]> getDownload(){
    URI end = URI.create(your url which server has exposed i.e. bla 
              bla/download);
    return rest.getForEntity(end,byte[].class);

}

public static void main(String[] args) throws Exception {


    byte[] byteArray = new TestClient().getDownload().getBody();
    FileOutputStream fos = new 
    FileOutputStream("C:\\WorkSpace\\testClient\\abc.txt");

     fos.write(byteArray);
     fos.close(); 
     System.out.println("file written successfully..");


}
Manas
  • 1
  • 1
0
//The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4"); 

FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);

//Now the bytes of the file are contain in the "byte[] data"
/*If you want to convert these bytes into a file, you have to write these bytes to a 
certain location, then it will make a new file at that location if same named file is 
not available at that location*/
FileOutputStream fileOutputStream =new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/Video.mp4");
fileOutputStream.write(data);
 /* It will write or make a new file named Video.mp4 in the "Download" directory of 
    the External Storage */
Usama Mehmood
  • 95
  • 1
  • 3