Does this block select an image or its path? - java

I understand that this code finds a photo via path but I don't understand what is in the photo variable
fileName = f.getAbsolutePath();
try {
File image2 = new File(fileName);
FileInputStream fis = new FileInputStream(image2);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for(int readNum; (readNum=fis.read(buf))!=-1;) {
bos.write(buf, 0, readNum);
}
photo = bos.toByteArray();
} catch(Exception e1) {
JOptionPane.showMessageDialog(null, e1);
}

The below code is just getting the byte array of that photo , that means the content of photo in byte array format.
fileName = f.getAbsolutePath();
try {
//Getting file object from the filePath
File image2 = new File(fileName);
// create input stream for that image object
FileInputStream fis = new FileInputStream(image2);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
// below repeated logic read the fis object till its empty and write into byte array object
for(int readNum; (readNum=fis.read(buf))!=-1;) {
bos.write(buf, 0, readNum);
}
photo = bos.toByteArray();
} catch(Exception e1) {
JOptionPane.showMessageDialog(null, e1);
}

Related

Getting blank zip file when getting created

I am getting blank zip even though I am writing images to it .Can some one let me know what I am doing wrong?I am trying to add images to the zip file .Its creating a zip file but with blank entry on it .so why its not writing the file to it?
int i = 0;
List<String> filenames = new ArrayList<String>();
for (Iterator iterator = datas.iterator(); iterator.hasNext();) {
byte[] bs = (byte[]) iterator.next();
BufferedImage image = null;
ByteArrayInputStream bis = new ByteArrayInputStream(bs);
image = ImageIO.read(bis);
bis.close();
// write the image to a file
File outputfile = new File("image" + i + ".jpg");
System.out.println("*************************" + outputfile.getAbsolutePath());
ImageIO.write(image, "jpg", outputfile);
i++;
filenames.add(outputfile.getAbsolutePath());
}
// Create the ZIP file
//create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipName);
//create object of ZipOutputStream from FileOutputStream
ZipOutputStream zout = new ZipOutputStream(fout);
byte[] buffer = new byte[2048];
for (int k = 0; k < filenames.size(); k++) {
FileInputStream fis = new FileInputStream(filenames.get(k).toString());
// Add ZIP entry to output stream.
File file = new File(filenames.get(k).toString());
String entryname = file.getName();
zout.putNextEntry(new ZipEntry(entryname));
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
zout.write(buffer, 0, bytesRead);
}
zout.closeEntry();
fis.close();
}
zout.flush();
fout.flush();
zout.close();
fout.close();

I have an one ArrayList storing few pdf files location in a directory. How to read the contents of pdf as array of bytes and Zip it

ArrayList is like this - [ Desktop/folder/abc.pdf, Desktop/folder/xyz.pdf ]
I am doing something like this
public byte[] compressByteArray(byte[] bytes){
ByteArrayOutputStream baos = null;
Deflater dfl = new Deflater();
dfl.setLevel(Deflater.BEST_COMPRESSION);
dfl.setInput(bytes);
dfl.finish();
baos = new ByteArrayOutputStream();
byte[] tmp = new byte[4*1024];
try{
while(!dfl.finished()){
int size = dfl.deflate(tmp);
baos.write(tmp, 0, size);
}
} catch (Exception ex){
} finally {
try{
if(baos != null) baos.close();
} catch(Exception ex){}
}
return baos.toByteArray();
}

Convert file to byte array then to string then to byte array then to the original file

I'm trying (In Java) to get a file document then convert it to bitArray afterwards to a String of similar representation, then back to the original bit array and finally to the original final document.
Here is my code, But the file generated is not viewable in this case the image.
try {
File file = new File("C:/Users/dkimigho/Downloads/kenyapowerlogo.jpg");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//create FileInputStream which obtains input bytes from a file in a file system
//FileInputStream is meant for reading streams of raw bytes such as 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;) {
//Writes to this byte array output stream
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(ARRAYBITStoPDF.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
System.out.println("byte1");
for (int i = 0; i < bytes.length; i++) {
System.out.print(bytes[i]);
}
//We have the bytes now convert to String
String stringbytearray=new String(bytes);
System.out.println("stringbytearray: "+stringbytearray);
//We have the bytes now convert to String
byte[] content = stringbytearray.getBytes();
System.out.println("byte2");
for (int i = 0; i < content.length; i++) {
System.out.print(content[i]);
}
int size = bytes.length;
InputStream isfilecontent = null;
byte[] b = new byte[size];
isfilecontent = new ByteArrayInputStream(content);
//writing the downloaded data into a PDF file
FileOutputStream fileOutputpdf = new FileOutputStream("C:/Users/dkimigho/Downloads/mykenyapowerlogo.jpg");
/* use binary I/O to prevent line based operation messing with the encoding.*/
byte[] buf2 = new byte[2048];
int b_read = 0;
while ( (b_read = isfilecontent.read(buf2)) > 0) {
fileOutputpdf.write(buf2, 0, b_read);
}
fileOutputpdf.flush();
//closed the output stream
fileOutputpdf.close();
} catch (IOException e) {
// handle IOException
System.out.println(e.getMessage());
}
Any help on pointing what I'm doing wrong? A correction of my code to a working one may be important.
I found an answer one has to use JAVA 8 java.util.Base64 to encode and decode the bytes without loosing information on the document. I hope it will be of help to someone.
/*
* 1. How to convert an image file to byte array?
*/
try {
File file = new File("C:/Users/qwerty/Downloads/factura.pdf");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//create FileInputStream which obtains input bytes from a file in a file system
//FileInputStream is meant for reading streams of raw bytes such as 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;) {
//Writes to this byte array output stream
bos.write(buf, 0, readNum);
// System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(ARRAYBITStoPDF.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
bos.close(); // should be inside a finally block
//We have the bytes now convert to String
// ENCODING
String encodedDoc= Base64.getEncoder().encodeToString(bytes);
System.out.println(encodedDoc);
// DECODING
int size = bytes.length;
InputStream isfilecontent = null;
//byte[] b = new byte[size];
isfilecontent = new ByteArrayInputStream(Base64.getDecoder().decode(encodedDoc));
//writing the downloaded data into a PDF file
FileOutputStream fileOutputpdf = new FileOutputStream("C:/Users/qwerty/Downloads/myfactura.pdf");
/* use binary I/O to prevent line based operation messing with the encoding.*/
byte[] buf2 = new byte[2048];
int b_read = 0;
while ( (b_read = isfilecontent.read(buf2)) > 0) {
fileOutputpdf.write(buf2, 0, b_read);
}
fileOutputpdf.flush();
//closed the output stream
fileOutputpdf.close();
} catch (IOException e) {
// handle IOException
System.out.println(e.getMessage());
}

Create ZIP from byte array [duplicate]

I am trying to convert an array of bytes into a ZIP file. I got bytes using the following code:
byte[] originalContentBytes= new Verification().readBytesFromAFile(new File("E://file.zip"));
private byte[] readBytesFromAFile(File file) {
int start = 0;
int length = 1024;
int offset = -1;
byte[] buffer = new byte[length];
try {
//convert the file content into a byte array
FileInputStream fileInuptStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInuptStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((offset = bufferedInputStream.read(buffer, start, length)) != -1) {
byteArrayOutputStream.write(buffer, start, offset);
}
bufferedInputStream.close();
byteArrayOutputStream.flush();
buffer = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
return buffer;
}
But my problem now is with converting the byte array back into a ZIP file - how can it be done?
Note : The specified ZIP contains two files.
To get the contents from the bytes you can use
ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry entry = null;
while ((entry = zipStream.getNextEntry()) != null) {
String entryName = entry.getName();
FileOutputStream out = new FileOutputStream(entryName);
byte[] byteBuff = new byte[4096];
int bytesRead = 0;
while ((bytesRead = zipStream.read(byteBuff)) != -1)
{
out.write(byteBuff, 0, bytesRead);
}
out.close();
zipStream.closeEntry();
}
zipStream.close();
You probably are looking for code like this:
ZipInputStream z = new ZipInputStream(new ByteArrayInputStream(buffer))
now you can get the zip file contents via getNextEntry()
Here is a helper method
private fun getZipData(): ByteArray {
val zipFile: File = getTempZipFile() // Return a zip File
val encoded = Files.readAllBytes(Paths.get(zipFile.absolutePath))
zipFile.delete() // If you wish to delete the zip file
return encoded
}

Android - file download problem - incomplete file

I have checked many code snippets, tried with and without buffer and I can't get to download whole file to SD card. The code I use currently is:
try {
url = new URL("http://mywebsite.com/directory/");
} catch (MalformedURLException e1) { }
String filename = "someKindOfFile.jpg"; // this won't be .jpg in future
File folder = new File(PATH); // TODO: add checking if folder exist
if (folder.mkdir()) Log.i("MKDIR", "Folder created");
else Log.i("MKDIR", "Folder not created");
File file = new File(folder, filename);
try {
conn = url.openConnection();
is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
is.close();
} catch (IOException e) { }
This code creates directory on SD card but downloads only 77 bytes of files. What might be the problem?
The error here is that he was writing the count variable converted to byte datatype instead of the bytes read from the input stream (those should be stored in a temporary byte[] buffer via bis.read(buffer))
The proper code block should be:
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(file);
int current = 0;
byte[] buffer = new byte[1024];
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.close();
is.close();

Categories