408

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.

0

12 Answers 12

616

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
}
7
  • 28
    @R. Bemrose Well, it probably manages to clean up resources in the sad case. Commented Dec 3, 2010 at 21:51
  • 2
    From the doc: NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.
    – bmargulies
    Commented Dec 3, 2010 at 21:51
  • 24
    If writing fails, you will leak the output stream. You should always use try {} finally {} to ensure proper resource cleanup. Commented Jun 8, 2013 at 6:40
  • 8
    the fos.close() statement is redundant since you're using try-with-resources which closes the stream automatically, even if writing fails. Commented Dec 4, 2017 at 16:51
  • 14
    Why would i use apache commons IO when it is 2 lines with regular Java
    – GabrielBB
    Commented Nov 19, 2018 at 1:49
230

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.

2
  • How about charset in this case?
    – Pavan
    Commented Aug 18, 2020 at 7: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. Commented Aug 20, 2020 at 3:55
161

Another solution using java.nio.file:

byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
4
  • 3
    I don't think C:\myfile.pdf would work on Android anyway... ;)
    – TBieniek
    Commented Jul 3, 2019 at 13:17
  • @TB How about charset in this case?
    – Pavan
    Commented Aug 18, 2020 at 7:28
  • 4
    charset seems irrelevant since we're writing bytes, not chars
    – TBieniek
    Commented Sep 14, 2020 at 9:24
  • What ever you said was true, I understood my mistake.
    – Pavan
    Commented Sep 14, 2020 at 10:38
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.

2
  • 7
    You could use Paths.get(filePath); instead of new File(filePath).toPath()
    – Tim Büthe
    Commented Jan 31, 2017 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." Commented Nov 22, 2017 at 13:56
20

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();
}
1
  • 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
    Commented Apr 16, 2018 at 18:28
4

Try an OutputStream or more specifically FileOutputStream

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) {}
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);
}
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);
                            }
2
  • 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
    Commented Apr 9, 2018 at 6: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. Commented Apr 10, 2018 at 9:56
1

I know it's done with InputStream

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

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.