byte[] to file in Java

JavaArraysFileIoInputstream

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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
}

Solution 2 - Java

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.

Solution 3 - Java

Another solution using java.nio.file:

byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);

Solution 4 - Java

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.

Solution 5 - Java

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

Solution 6 - Java

Try an OutputStream or more specifically FileOutputStream

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

> I know it's done with InputStream

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

Solution 11 - Java

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

Solution 12 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionelcoolView Question on Stackoverflow
Solution 1 - JavabmarguliesView Answer on Stackoverflow
Solution 2 - JavaSharkAlleyView Answer on Stackoverflow
Solution 3 - JavaTBieniekView Answer on Stackoverflow
Solution 4 - JavaEngineerWithJava54321View Answer on Stackoverflow
Solution 5 - JavaVoicuView Answer on Stackoverflow
Solution 6 - JavaGareth DavisView Answer on Stackoverflow
Solution 7 - Javabarti_dduView Answer on Stackoverflow
Solution 8 - JavaPiyush RumaoView Answer on Stackoverflow
Solution 9 - JavaPiyush RumaoView Answer on Stackoverflow
Solution 10 - JavaPowerlordView Answer on Stackoverflow
Solution 11 - JavaYogiView Answer on Stackoverflow
Solution 12 - Javayegor256View Answer on Stackoverflow