Saving a spreadsheet to disk using java - 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.

Related

Convert BLOB to PDF

I have a BLOB file which I have got from the DB team. I know that its a PDF document (I opened using Notepad++ and I could see the file name) and I need to convert the same using java. I have checked for few examples and I couldn't find any example where the BLOB file itself is taken as an input instead of taking directly from the DB (Resultset). Can anyone please give some pointers as to how I can accomplish this?
Thanks in advance!
I have tried below,
File file = new File("C:/Users/User1/Desktop/0LK54E33K1477e2MCEU25JV0G8MG418S007N45JU.BLOB0");
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("C:/Users/User1/Desktop/Test.pdf");
FileOutputStream fos = new FileOutputStream(someFile);
fos.write(bytes);
fos.flush();
fos.close();

Readinga file in java

what i was trying to do was copying a content of file using File using File input stream and writing it in to another file
InputStream is = null;
FileOutputStream fos=null;
try{
is = new FileInputStream("D:\\helloworld.txt");
fos = new FileOutputStream("D:\\helloworld1.txt");
byte[] buffer = new byte[255];
while(is.read(buffer)>-1){
fos.write(is.read(buffer,0,buffer.length));
}
is.close();
fos.close();
}catch(Exception e){
}
}
content of helloworld:
vsdaewfscvadfdsohcdvwbuivbASJXBBfjbzx cidbv k ab SifvicvahisvcbxsiSDobhsxcb Z asvfuigevwifuvweivfb
output of helloworld is:
ΓΏ
int r=0;
while((r=is.read(buffer))>-1){
fos.write(buffer,0,r);
}
You're reading into buffer twice and writing the number of bytes read...

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

How To : Write a File with FileOutputStream?

What I'm doing is that the file and each line of data I'm reading for BufferOutputStream will be saved in a FileOutputStream and I want to specify the output data.
If i have understood correct, you want to download the file from S3 and write to your local directory using BufferedOutputStream .
S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
InputStream is = object.getObjectContent();
// Creating file
File file= new File(localFilePath);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos= new BufferedOutputStream(fos);
int read = -1;
while ((read = is.read()) != -1) {
bos.write(read);
}
bos.flush();
bos.close();
is.close();

Java: Need to create PDF from byte-Array

From a DB2 table I've got blob which I'm converting to a byte array so I can work with it. I need to take the byte array and create a PDF out of it.
This is what I have:
static void byteArrayToFile(byte[] bArray) {
try {
// Create file
FileWriter fstream = new FileWriter("out.pdf");
BufferedWriter out = new BufferedWriter(fstream);
for (Byte b: bArray) {
out.write(b);
}
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
But the PDF it creates is not right, it has a bunch of black lines running from top to bottom on it.
I was actually able to create the correct PDF by writing a web application using essentially the same process. The primary difference between the web application and the code about was this line:
response.setContentType("application/pdf");
So I know the byte array is a PDF and it can be done, but my code in byteArrayToFile won't create a clean PDF.
Any ideas on how I can make it work?
Sending your output through a FileWriter is corrupting it because the data is bytes, and FileWriters are for writing characters. All you need is:
OutputStream out = new FileOutputStream("out.pdf");
out.write(bArray);
out.close();
One can utilize the autoclosable interface that was introduced in java 7.
try (OutputStream out = new FileOutputStream("out.pdf")) {
out.write(bArray);
}
Read from file or string to bytearray.
byte[] filedata = null;
String content = new String(bytearray);
content = content.replace("\r", "").replace("\uf8ff", "").replace("'", "").replace("\"", "").replace("`", "");
String[] arrOfStr = content.split("\n");
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
// setting font family and font size
cs.beginText();
cs.setFont(PDType1Font.HELVETICA, 14);
cs.setNonStrokingColor(Color.BLACK);
cs.newLineAtOffset(20, 750);
for (String str: arrOfStr) {
cs.newLineAtOffset(0, -15);
cs.showText(str);
}
cs.newLine();
cs.endText();
}
document.save(znaFile);
document.close();
public static String getPDF() throws IOException {
File file = new File("give complete path of file which must be read");
FileInputStream stream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;enter code here
while ((bytesRead = stream.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
System.out.println("it came back"+baos);
byte[] buffer1= baos.toByteArray();
String fileName = "give your filename with location";
//stream.close();
FileOutputStream outputStream =
new FileOutputStream(fileName);
outputStream.write(buffer1);
return fileName;
}

Categories

Resources