Create a file from a ByteArrayOutputStream - java

Can someone explain how I can get a file object if I have only a ByteArrayOutputStream. How to create a file from a ByteArrayOutputStream?

You can do it with using a FileOutputStream and the writeTo method.
ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
byteArrayOutputStream.writeTo(outputStream);
}
Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

You can use a FileOutputStream for this.
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}

Related

Compressing byte[] to byte[] with GZIPOutputStream? Unexpected end of ZLIB input stream

I am trying to compress and array of bytes into another array of bytes using GZIPOutputStream (in Java).
This is my code:
#Test
public void testCompressBytes() throws IOException {
final byte[] uncompressed = RandomStringUtils.randomAlphanumeric(100000 /* 100 kb */).getBytes();
// compress
byte[] compressed;
try (InputStream is = new ByteArrayInputStream(uncompressed);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream os = new GZIPOutputStream(baos)) {
IOUtils.copy(is, os); // org.apache.commons.io
os.flush();
compressed = baos.toByteArray();
}
System.out.println("Size before compression = " + uncompressed.length + ", after = " + compressed.length);
// decompress back
byte[] decompressedBack;
try (InputStream is = new GZIPInputStream(new ByteArrayInputStream(compressed));
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
IOUtils.copy(is, baos); // EXCEPTION THROWN HERE
baos.flush();
decompressedBack = baos.toByteArray();
}
assertArrayEquals(uncompressed, decompressedBack);
}
And this is the output I'm getting:
Size before compression = 100000, after = 63920
java.io.EOFException: Unexpected end of ZLIB input stream
What could I be doing wrong?
You need to call GZIPOutputStream::close before calling ByteArrayOutputStream::toByteArray, so that GZIPOutputStream writes all the end bits.
In your current code you are calling ByteArrayOutputStream::toByteArray before GZIPOutputStream::close (via try-with-resources) that's why it doesn't work.
Thanks, everybody!
Although calling GZIPOutputStream::finish() before ByteArrayOutputStream::toByteArray() seems to do the trick, I believe it's better to completely close the GZIP stream first, which in turn forces us to keep ByteArrayOutputStream outside the try-with-resources clause.
So, my reworked compression part looks like that now:
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (InputStream is = new ByteArrayInputStream(uncompressed);
GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
IOUtils.copy(is, gzos);
} catch (final IOException e) {
throw new RuntimeException(e);
}
IOUtils.closeQuietly(baos);
final byte[] compressed = baos.toByteArray();

Saving a spreadsheet to disk using java

I have a requirement to store the uploaded spreadsheet to the disk. I am using the below code to do the same and receiving the file is corrupted error from the excel.
byte[] bytes = null;
File uploadedFile = new File("D://xlsxTest//BNG Issue.xlsx");
File file = new File("D://xlsxTest//sample1.xlsx");
FileOutputStream outStream = null;
InputStream inputStream = null;
try{
if(!file.exists()){
file.createNewFile();
}
outStream = new FileOutputStream(file);
if (uploadedFile != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
inputStream = new FileInputStream(uploadedFile);;
int c = 0;
while (c != -1) {
c = inputStream.read();
byteArrayOutputStream.write((char) c);
}
bytes = byteArrayOutputStream.toByteArray();
}
outStream.write(bytes);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
I tried using a file of 83KB size and the resultant file is 82.5KB.
Any help would be appreciated.
Thanks.
Try using Apace POI, Convert .xls or .xlsx file to byte array using OPCPackage and XSSFWorkbook with below code.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OPCPackage pkg = OPCPackage.open(new File(fullFileName));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
wb.write(baos);
byte[] fileContent = baos.toByteArray();
Apache POI takes care to extract all information of the excel file while converting to byte array.

Java ObjectOutputStream Not Writing to ZipEntry

I am trying to serialize an object into a ZipEntry using an ObjectOutputStream, however it doesn't appear to be writing anything because when I print the byte array produced, it shows null. I tried writing a string with the ZipOutputStream, and upon printing the resulting byte array got a sizeable result. SO my question is: why is the objectoutput stream not correctly writing into the ZipEntry. (ConfigEntry does implement Serializable).
String s = "Tired, Exhausted";
ConfigEntry con = new ConfigEntry("rand", "random", 3);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry("test.txt");
ObjectOutputStream obs = new ObjectOutputStream(zos);
zos.putNextEntry(entry);
obs.writeObject(con);
obs.close();
zos.closeEntry();
zos.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
os = bs.getOutputStream();
byte[] result = baos.toByteArray();
String test = new String(result, "UTF-8");
Log.v("Mac Address", test);
Log.v("Mac Address", Arrays.toString(result));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
This baos goes out of scope after the try block. You are writing to one baos and you are looking into another baos declared in an outer scope, probably an instance member of the class.

How to return outputstream of .xlsx file

in a java-class i just created workbook like this
XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(fis);
and filled cells with its corresponding celltype.
now i need to write it as a xxx.xlsx file same time return a BuyteArrayOutputStream.
to do so,
FileOutputStream fos = new FileOutputStream(tempFile);
workbook.write(fos);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
return outputStream;
here writing xxx.xlsx fils done successfully but same time it returns outputStream as null?
How do achieve it both?
first i write it into the outputstream and get byte[]. after that through IOUtils.write() from Apache Commons IO writing as a file later.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
byte[] b = outputStream.toByteArray();
FileOutputStream fos = new FileOutputStream(tempFile);
IOUtils.write(b, fos);
return outputStream;

how to convert image to byte array in java?(With out using buffered image)

Hi could anyone please explain me how to convert the image data to byte array in java I am trying like this.I do not need to use buffered image here.
File file = new File("D:/img.jpg");
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
You can convert your image data using FileInputStream also.
File file = new File("D:\\img.jpg");
FileInputStream fis = new FileInputStream(file);
//Now try to create FileInputStream which obtains input bytes from a file.
//FileInputStream is meant for reading streams of raw bytes,in this case its image data.
//For reading streams of characters, consider using FileReader.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
//Now Write to this byte array output stream
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
or you could use:
Image image = Toolkit.getDefaultToolkit().getImage("D:/img.jpg");
byte[] imageBytes = getImageBytes(image);
private byte[] getImageBytes(Image image) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(image, "bmp", baos);
baos.flush();
return baos.toByteArray();
}
}

Categories

Resources