Itext GifImage first inputstream not closed - java

I have a problem with the com.itextpdf.text.pdf.codec.GifImage.
In the constructor GifImage(URL url) the inputstream is used twice but only once closed.
If the stream isn't closed the file (temporary image) can not be deleted.
public GifImage(URL url) throws IOException {
fromUrl = url;
InputStream is = null;
try {
is = url.openStream(); // first use
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
baos.write(bytes, 0, read);
}
is = new ByteArrayInputStream(baos.toByteArray()); // second use
baos.flush();
baos.close();
process(is);
}
finally {
if (is != null) {
is.close();
}
}
}

This should solve your problem:

Related

Download Image from Url and covert into byte array - android

I'm receiving URL of images and other data from API and showing images into recyclerview, I want to store images in room database in a byte array format, but I'm getting an error while converting image URL to a byte array. My app is crashing at url.openstream();.
private byte[] getByteArrayImage(String imageUrl) {
URL url = null;
try {
url = new URL(imageUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
byte[] chunk = new byte[4096];
int bytesRead;
InputStream stream = url.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
url.openStream().close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return outputStream.toByteArray();
}
There are a couple of problems with your code:
As already noted in a comment, you call openStream() twice.
If an exception occurs, close() won't be called in your code. Use try-with-resources instead.
Propagate exceptions to the caller. The caller will generally want to know the exception message.
Don't ever use printStackTrace(). This is the worst way to report errors.
After the first printStackTrace(), you continue with a null URI, which will cause a NullPointerException.
The method should be static.
Here's how I would write this:
private static byte[] getImageBytes(String imageUrl) throws IOException
{
URL url = new URL(imageUrl);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (InputStream stream = url.openStream())
{
byte[] buffer = new byte[4096];
while (true)
{
int bytesRead = stream.read(buffer);
if (bytesRead < 0) { break; }
output.write(buffer, 0, bytesRead);
}
}
return output.toByteArray();
}
I recommend below pseudo code to read data from URL:
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
URL url = new URL("you'r address");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
StringBuffer sb = new StringBuffer();
int r;
while((r = isr.read()) != -1)
{
sb.append(r);
}
byte buffer[] = sb.toString().getBytes();
}
catch (MalformedURLException e)
{
e.printStackTrace();
Log.i("tag" , "MalformedURLException"+e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.i("tag" , "IOException"+e.getMessage());
}
}
});
t.start();

Unzipping an image failing using buffer from gzip format

I am zipping the files using , but while unzipping them, I am facing two problems,
when unzipped without buffer its getting back to original form, but when I use buffer its not able to do it correctly.
the size of the unzipped file is more than the original file.
private static void writeFile(FileOutputStream fos, String zipFilePath) throws IOException {
try (FileInputStream fis = new FileInputStream(zipFilePath);
GZIPInputStream inflaterInputStream = new GZIPInputStream(fis)) {
int data;
**while ((data = inflaterInputStream.read()) != -1) {//without buffer**
fos.write(data);
}
}
}
private static void writeFile(FileOutputStream fos, String zipFilePath) throws IOException {
byte[] buffer = new byte[12048];
try (FileInputStream fis = new FileInputStream(zipFilePath);
GZIPInputStream inflaterInputStream = new GZIPInputStream(fis)) {
int data;
**while ((data = inflaterInputStream.read(buffer)) != -1) {//with buffer**
fos.write(data);
}
}
}
You're not writing the buffer, but data which is the length of bytes read...
Corrected:
private static void writeFile(FileOutputStream fos, String zipFilePath) throws IOException {
byte[] buffer = new byte[12048];
try (InputStream fis = new FileInputStream(zipFilePath);
InputStream inflaterInputStream = new GZIPInputStream(fis)) {
int data;
while ((data = inflaterInputStream.read(buffer)) != -1) {//with buffer**
fos.write(buffer, 0, data);
}
}
}
You'd be better off using apache.commons-io
private static void writeFile(FileOutputStream fos, String zipFilePath) throws IOException {
try (InputStream fis = new FileInputStream(zipFilePath);
InputStream inflaterInputStream = new GZIPInputStream(fis)) {
IOUtils.copy(fis, fos);
}
}

Get progress of readBytes in android

I've already seen
Is it possible to check progress of URLconnection.getInputStream()?
https://stackoverflow.com/a/20120451/5437621
I'm using the following code to download a file from internet:
try {
InputStream is = new URL(pdfUrl).openStream();
byte[] pdfData = readBytes(is);
return pdfData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
public byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Is there any method I can get the progress of the file being downloaded ?
The answers I have seen are using a while loop but I don't understand how to use it in this case.
EDIT:
I'm using this in AsyncTask:
protected byte[] doInBackground(String... url) {
pdfUrl = url[0];
try {
InputStream is = new URL(pdfUrl).openStream();
DownloadBytes downloadData = readBytes(is);
byte[] pdfData = downloadData.getBytes();
progress = downloadData.getProgress();
return pdfData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
How can I adjust publishProgress() in this method ?

Transfer file from client to server over socket in java

I am trying to upload a file from a client to the server using sockets in JAVA. It is partially working, however, the file that gets created on the server is an empty text file. Can anyone offer any suggestions as to where I may have an issue. Thanks:
Server:
private void handleFileUpload(String fileSizeInBytes, String fileName) throws IOException{
String fullyQualifiedFileName = rootDirectory+System.getProperty("file.separator")+fileName;
File fileToWrite = new File(fullyQualifiedFileName);
if(fileToWrite.exists()){
fileToWrite.delete();
}
int bytesRead = 0;
byte[] aByte = new byte[1];
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ByteArrayOutputStream baos = null;
try {
inputStream = socket.getInputStream();
fileOutputStream = new FileOutputStream(fullyQualifiedFileName);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(aByte, 0, aByte.length);
baos = new ByteArrayOutputStream();
do {
baos.write(aByte);
bytesRead = inputStream.read(aByte);
} while (bytesRead != -1);
bufferedOutputStream.write(baos.toByteArray());
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Client:
private void uploadFile(Socket socket, File fileToUpload){
byte[] mybytearray = new byte[(int) fileToUpload.length()];
try {
FileInputStream fis = new FileInputStream(fileToUpload);
BufferedOutputStream toServer = new BufferedOutputStream(socket.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
toServer.write(mybytearray, 0, mybytearray.length);
toServer.flush();
toServer.close();
return;
} catch (IOException ex) {
handleServerError("upload file", ex);
System.exit(0);
}
Change your handleFileUpload method as following
private void handleFileUpload(String fileSizeInBytes, String fileName) throws IOException{
String fullyQualifiedFileName = rootDirectory+System.getProperty("file.separator")+fileName;
File fileToWrite = new File(fullyQualifiedFileName);
if(fileToWrite.exists()){
fileToWrite.delete();
}
int bytesRead = 0;
byte[] aByte = new byte[1024];
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ByteArrayOutputStream baos = null;
try {
inputStream = socket.getInputStream();
fileOutputStream = new FileOutputStream(fullyQualifiedFileName);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(aByte, 0, aByte.length);
while (bytesRead != -1) {
bufferedOutputStream.write(aByte, 0, bytesRead);
bytesRead = inputStream.read(aByte, 0, aByte.length);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Compressing byte arrays using GZIP in java

I've been working on a function that compresses an array of bytes using GZIP and sends it through an outputStream that belongs to a socket. It downloads fine but when trying to decompress on my PC it says that file is corrupted.
private void Zip(byte[] datatocompress)
{
ZipOutputStream zippoutstream = new ZipOutputStream(outputstream);
zippoutstream.putNextEntry(new ZipEntry("file.html"));
zippoutstream.write(datatocompress);
zippoutstream.closeEntry();
zippoutstream.flush();
zippoutstream.close();
}
No idea about what crashes. Any suggestion?
public static byte[] gzip(byte[] val) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(val.length);
GZIPOutputStream gos = null;
try {
gos = new GZIPOutputStream(bos);
gos.write(val, 0, val.length);
gos.finish();
gos.flush();
bos.flush();
val = bos.toByteArray();
} finally {
if (gos != null)
gos.close();
if (bos != null)
bos.close();
}
return val;
}
/**
* Compress
*
* #param source
*
* #param target
*
* #throws IOException
*/
public static void zipFile(String source, String target) throws IOException {
FileInputStream fin = null;
FileOutputStream fout = null;
GZIPOutputStream gzout = null;
try {
fin = new FileInputStream(source);
fout = new FileOutputStream(target);
gzout = new GZIPOutputStream(fout);
byte[] buf = new byte[1024];
int num;
while ((num = fin.read(buf)) != -1) {
gzout.write(buf, 0, num);
}
} finally {
if (gzout != null)
gzout.close();
if (fout != null)
fout.close();
if (fin != null)
fin.close();
}
}

Categories

Resources