[java] byte[] to file in Java

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.

This question is related to java arrays file io inputstream

The answer is


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

Try an OutputStream or more specifically FileOutputStream


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

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.


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.


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

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


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

Another solution using java.nio.file:

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

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


I know it's done with InputStream

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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to io

Reading file using relative path in python project How to write to a CSV line by line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder Exception: Unexpected end of ZLIB input stream How to get File Created Date and Modified Date Printing Mongo query output to a file while in the mongo shell Load data from txt with pandas Writing File to Temp Folder How to get resources directory path programmatically ValueError : I/O operation on closed file

Examples related to inputstream

Convert InputStream to JSONObject How to read all of Inputstream in Server Socket JAVA Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList? How to create streams from string in Node.Js? How can I read a text file in Android? Can you explain the HttpURLConnection connection process? Open URL in Java to get the content How to convert byte[] to InputStream? Read input stream twice AmazonS3 putObject with InputStream length example