401

With Java:

I have a byte[] that represents a file.

How do I write this to a file (ie. C:\myfile.pdf)

I know it's done with InputStream, but I can't seem to work it out.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
elcool
  • 6,041
  • 7
  • 29
  • 44

12 Answers12

609

Use Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

Or, if you insist on making work for yourself...

try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
   //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
Community
  • 1
  • 1
bmargulies
  • 97,814
  • 39
  • 186
  • 310
226

Without any libraries:

try (FileOutputStream stream = new FileOutputStream(path)) {
    stream.write(bytes);
}

With Google Guava:

Files.write(bytes, new File(path));

With Apache Commons:

FileUtils.writeByteArrayToFile(new File(path), bytes);

All of these strategies require that you catch an IOException at some point too.

Dónal
  • 185,044
  • 174
  • 569
  • 824
SharkAlley
  • 11,399
  • 5
  • 51
  • 42
  • How about charset in this case? – Pavan Aug 18 '20 at 07:28
  • 2
    @pavan charset of `path`? FileOutputStream documentation does not mention this so this is probably platform-specific. I'd guess it is UTF-8 in the absolute most cases. `bytes` are written as-is, no charset is involved. – Alexey Nezhdanov Aug 20 '20 at 03:55
158

Another solution using java.nio.file:

byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
TBieniek
  • 4,858
  • 2
  • 24
  • 29
47

Also since Java 7, one line with java.nio.file.Files:

Files.write(new File(filePath).toPath(), data);

Where data is your byte[] and filePath is a String. You can also add multiple file open options with the StandardOpenOptions class. Add throws or surround with try/catch.

EngineerWithJava54321
  • 1,215
  • 2
  • 15
  • 18
  • 7
    You could use `Paths.get(filePath);` instead of `new File(filePath).toPath()` – Tim Büthe Jan 31 '17 at 11:49
  • @Halil I don't think that's right. According to the javadocs there is an optional 3rd argument for open options and "If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0." – Kevin Sadler Nov 22 '17 at 13:56
21

From Java 7 onward you can use the try-with-resources statement to avoid leaking resources and make your code easier to read. More on that here.

To write your byteArray to a file you would do:

try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
    fos.write(byteArray);
} catch (IOException ioe) {
    ioe.printStackTrace();
}
Voicu
  • 16,921
  • 10
  • 60
  • 69
  • I tried using this and it caused problems with bytes that weren't UTF-8 characters, so I would be careful with this one if you're trying to write individual bytes to build a file, for example. – pdrum Apr 16 '18 at 18:28
4

Try an OutputStream or more specifically FileOutputStream

Gareth Davis
  • 27,701
  • 12
  • 73
  • 106
4

Basic example:

String fileName = "file.test";

BufferedOutputStream bs = null;

try {

    FileOutputStream fs = new FileOutputStream(new File(fileName));
    bs = new BufferedOutputStream(fs);
    bs.write(byte_array);
    bs.close();
    bs = null;

} catch (Exception e) {
    e.printStackTrace()
}

if (bs != null) try { bs.close(); } catch (Exception e) {}
barti_ddu
  • 10,179
  • 1
  • 45
  • 53
2
File f = new File(fileName);    
byte[] fileContent = msg.getByteSequenceContent();    

Path path = Paths.get(f.getAbsolutePath());
try {
    Files.write(path, fileContent);
} catch (IOException ex) {
    Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
Alexey Subach
  • 11,903
  • 7
  • 34
  • 60
Piyush Rumao
  • 363
  • 4
  • 7
2

////////////////////////// 1] File to Byte [] ///////////////////

Path path = Paths.get(p);
                    byte[] data = null;                         
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
                    }

/////////////////////// 2] Byte [] to File ///////////////////////////

 File f = new File(fileName);
 byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
                            try {
                                Files.write(path, fileContent);
                            } catch (IOException ex) {
                                Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
                            }
Piyush Rumao
  • 363
  • 4
  • 7
  • Thanks for answer..but i have confusion regarding "fileName" i mean what is the type of file you are saving the data? can you please explain? – SRam Apr 09 '18 at 06:40
  • 1
    Hi SRam, that solely depends on your application why you are doing the conversion and in which format you want the output, I would suggest to go for a .txt format (e.g:- myconvertedfilename.txt) but again its your choice. – Piyush Rumao Apr 10 '18 at 09:56
1

This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.

`Enter code here

import java.io.File;   
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;        

//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//     

public class ReadandWriteAByte {
    public void readandWriteBytesToFile(){
        File file = new File("count.char"); //(abcdefghijk)
        File bfile = new File("bytefile.txt");//(New File)
        byte[] b;
        FileInputStream fis = null;              
        FileOutputStream fos = null;          

        try{               
            fis = new FileInputStream (file);           
            fos = new FileOutputStream (bfile);             
            b = new byte [1024];              
            int i;              
            StringBuilder sb = new StringBuilder();

            while ((i = fis.read(b))!=-1){                  
                sb.append(new String(b,5,5));               
                fos.write(b, 2, 5);               
            }               

            System.out.println(sb.toString());               
        }catch (IOException e) {                    
            e.printStackTrace();                
        }finally {               
            try {              
                if(fis != null);           
                    fis.close();    //This helps to close the stream          
            }catch (IOException e){           
                e.printStackTrace();              
            }            
        }               
    }               

    public static void main (String args[]){              
        ReadandWriteAByte rb = new ReadandWriteAByte();              
        rb.readandWriteBytesToFile();              
    }                 
}                

O/P in console : fghij

O/P in new file :cdefg

Axe
  • 6,285
  • 3
  • 31
  • 38
Yogi
  • 21
  • 1
1

I know it's done with InputStream

Actually, you'd be writing to a file output...

Powerlord
  • 87,612
  • 17
  • 125
  • 175
0

You can try Cactoos:

new LengthOf(new TeeInput(array, new File("a.txt"))).value();

More details: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html

yegor256
  • 102,010
  • 123
  • 446
  • 597