问题
I want to convert FileOutputStream to Byte array for passing binary data between two applications. please any one can help?
回答1:
To convert a file to byte array, ByteArrayOutputStream class is used. This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().
To convert byte array back to the original file, FileOutputStream class is used. A file output stream is an output stream for writing data to a File or to a FileDescriptor.
The following code has been fully tested.
public static void main(String[] args) throws FileNotFoundException, IOException {
File file = new File("java.pdf");
FileInputStream fis = new FileInputStream(file);
//System.out.println(file.exists() + "!!");
//InputStream in = resource.openStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
//below is the different part
File someFile = new File("java2.pdf");
FileOutputStream fos = new FileOutputStream(someFile);
fos.write(bytes);
fos.flush();
fos.close();
}
how to write a byte array to a file using a FileOutputStream. The FileOutputStream is an output stream for writing data to a File or to a FileDescriptor.
public static void main(String[] args) {
String s = "input text to be written in output stream";
File file = new File("outputfile.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// Writes bytes from the specified byte array to this file output stream
fos.write(s.getBytes());
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while writing file " + ioe);
}
finally {
// close the streams using close method
try {
if (fos != null) {
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
}
回答2:
You may use ByteArrayOutputStream
like that
private byte[] filetoByteArray(String path) {
byte[] data;
try {
InputStream input = new FileInputStream(path);
int byteReads;
ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
while ((byteReads = inputStream.read()) != -1) {
output.write(byteReads);
}
data = output.toByteArray();
output.close();
input.close();
return data;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
来源:https://stackoverflow.com/questions/36404949/is-possible-to-convert-fileoutputstream-to-byte-array