Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write byte[] to File in Java [closed]

How to convert byte array to File in Java?

byte[] objFileBytes, File objFile 
like image 223
farajnew Avatar asked Jul 26 '11 10:07

farajnew


People also ask

What does byte [] do in Java?

A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.

How do you write a byte array?

In short, to write a byte array to a file using a FileOutputStream you should: Create a new File instance by converting the given pathname string into an abstract pathname. Create a new FileOutputStream to write to the file represented by the specified File object.

How do I create a byte file?

write(bytes, new File(path)); With Apache Commons: FileUtils. writeByteArrayToFile(new File(path), bytes);

Which stream is used to write a byte array to a file?

Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later. The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.


1 Answers

A File object doesn't contain the content of the file. It is only a pointer to the file on your hard drive (or other storage medium, like an SSD, USB drive, network share). So I think what you want is writing it to the hard drive.

You have to write the file using some classes in the Java API

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(yourFile)); bos.write(fileBytes); bos.flush(); bos.close(); 

You can also use a Writer instead of an OutputStream. Using a writer will allow you to write text (String, char[]).

BufferedWriter bw = new BufferedWriter(new FileWriter(yourFile)); 

Since you said you wanted to keep everything in memory and don't want to write anything, you might try to use ByteArrayInputStream. This simulates an InputStream, which you can pass to the most of the classes.

ByteArrayInputStream bais = new ByteArrayInputStream(yourBytes); 
like image 57
Martijn Courteaux Avatar answered Oct 04 '22 06:10

Martijn Courteaux