ChatGPT解决这个技术问题 Extra ChatGPT

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.


C
Community

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
}

@R. Bemrose Well, it probably manages to clean up resources in the sad case.
From the doc: NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.
If writing fails, you will leak the output stream. You should always use try {} finally {} to ensure proper resource cleanup.
the fos.close() statement is redundant since you're using try-with-resources which closes the stream automatically, even if writing fails.
Why would i use apache commons IO when it is 2 lines with regular Java
D
Dónal

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.


How about charset in this case?
@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.
T
TBieniek

Another solution using java.nio.file:

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

I don't think C:\myfile.pdf would work on Android anyway... ;)
@TB How about charset in this case?
charset seems irrelevant since we're writing bytes, not chars
What ever you said was true, I understood my mistake.
E
EngineerWithJava54321

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.


You could use Paths.get(filePath); instead of new File(filePath).toPath()
@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."
V
Voicu

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

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.
G
Gareth Davis

Try an OutputStream or more specifically FileOutputStream


b
barti_ddu

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

A
Alexey Subach
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);
}

P
Piyush Rumao

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

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?
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.
P
Powerlord

I know it's done with InputStream

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


A
Axe

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


y
yegor256

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