Read form ZipDecryptInputStream and write it to OutputStream - java

public void decrypt(String inputFile, String password) {
ZipDecryptInputStream zipDecrypt = null;
try {
zipDecrypt = new ZipDecryptInputStream(new FileInputStream(
inputFile), password);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File file = new File("outouttfile.tsv");
OutputStream fop = null;
try {
fop = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zipDecrypt.read(buffer)) != -1) {
fop.write(buffer, 0, bytesRead);
System.out.println("Written");
}
} catch (IOException e) {
e.printStackTrace();
}
}
My while loop becomes an infinite loop and does not stop reading the file even its read once. Any idea why?

Related

Delete a directory after untar a file

I have a .tar.gz file and I want to untar that same file.
To do that I have this function in java:
private void unTarFile(String tarFile, File destFile) {
TarArchiveInputStream tis = null;
FileInputStream fis = null;
GZIPInputStream gzipInputStream = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(tarFile);
bis = new BufferedInputStream(fis);
// .gz
gzipInputStream = new GZIPInputStream(bis);
// .tar.gz
tis = new TarArchiveInputStream(gzipInputStream);
TarArchiveEntry tarEntry = null;
while ((tarEntry = tis.getNextTarEntry()) != null) {
System.out.println(" tar entry- " + tarEntry.getName());
if (tarEntry.isDirectory()) {
continue;
} else {
// In case entry is for file ensure parent directory is in place
// and write file content to Output Stream
File outputFile = new File(destFile + File.separator + tarEntry.getName());
outputFile.getParentFile().mkdirs();
IOUtils.copy(tis, new FileOutputStream(outputFile));
}
}
} catch (IOException ex) {
System.out.println("Error while untarring a file- " + ex.getMessage());
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (gzipInputStream != null) {
try {
gzipInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (tis != null) {
try {
tis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
This works and I can untar my .tar.gz successfully.
I can edit the files of the untarred directory to, but when I try to delete my directory I cant:
Did I forgot to close something?

How to send a bitmap using serversocket

I am making a multiplayer drawing application for android and I need to send the drawings that every user made to one player. I am using a server socket for this.
First thing I do is convert the Bitmap to a byte array, so I can send it to the Host with host.write(byteArray);
Bitmap bitmapImage = drawView.getBitmap();
byte[] byteArray = getByteArray(bitmapImage);
byteArrayLength = byteArray.length;
MainWifiActivity.SendReceive host = MainWifiActivity.sendReceiveHost;
if (host != null) {
host.write(byteArray);
}
The following code is my SendReceive class, which listenes to the inputStream and then starts a Handler, that is supposed to save the Bitmap to Internal Storage
public class SendReceive extends Thread {
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket s) {
socket = s;
try {
inputStream = s.getInputStream();
outputStream = s.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
int filesize;
while (socket != null) {
try {
filesize = DrawingActivity.byteArrayLength;
if(buffer.length != filesize && filesize > 0){
buffer = new byte[filesize];
}
bytes = inputStream.read(buffer,0 ,buffer.length);
if (bytes > 0) {
Message mesg = handler.obtainMessage(IMAGE_MSG, bytes, -1, buffer);
mesg.sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And the Handler:
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case IMAGE_MSG:
byte[] byteArray = (byte[]) msg.obj;
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
saveBitmapToInternalStorage(bitmap);
}
return false;
}
});
In the saveBitmapToInternalStorage Method I get a java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
private void saveBitmapToInternalStorage(Bitmap bmp) {
File directory = getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory, UUID.randomUUID().toString() + ".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
Log.d("HELLO", "MY ERROR: " + e);
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I know that BitmapFactory.decodeByteArray returns the decoded bitmap, or null if the image could not be decoded.
But why could it not be decoded?
I think this piece is wrong
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
It should be
FileOutputStream fos = new FileOutputStream(myPath);
try {
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {

Catch 404 error from BufferedInputStream

I have a function for html page download.
Here is the code:
public class pageDownload {
public static void down(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(new File(filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
in.close();
fout.close();
}
}
Works ok, problem appears when i try to download a page that not exist. I can't figure out how to handle 404 error in this case.
Has anyone some idea?
Do you mean something like this? I added a finally to save close the Streams
public class pageDownload {
public static void down(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(new File(filename));
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch(FileNotFoundException ex)
{
System.err.println("Caught 404: " + e.getMessage());
}
catch(IOException ex)
{
System.err.println("Caught IOException: " + e.getMessage());
}
catch(IndexOutOfBoundsException e)
{
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
finally{
if(in != null)
try { in.close(); } catch ( IOException e ) { }
if(fout != null)
try { fout.close(); } catch ( IOException e ) { }
}
}
}
Your problem is you get a NullPointerException when you try to close the streams. You should anyway close them in a finally clause or use try with resources:
public static void down(final String filename, final String urlString)
throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new URL(urlString)
.openStream());
FileOutputStream fout = new FileOutputStream(new File(filename))) {
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
}

Sending an image through socket as byte array in Java

I know this has been asked in a few different ways, but I've been working on this for 2 days with no avail. My code is failing in that the receiving side throws EOF exceptions constantly. Can someone point me in the right direction?
Receiving side:
class ReceiveThread extends Thread {
ReceiveThread() {
}
#Override
public void run() {
System.out.println("Receive Thread Start");
DataInputStream in;
try {
} catch (Exception e) {
return;
}
try {
in = new DataInputStream(connection.getInputStream());
while (true) {
if (!connection.isConnected()) {
System.out.println("Connection not connected");
break;
}
try {
int len = in.readInt();
byte[] data = new byte[len];
System.out.println("Image size: " + len);
if (len > 0) {
in.readFully(data, 0, len);
BufferedImage bi = ImageIO.read(new ByteArrayInputStream(data));
panel.updateImage(bi);
panel.repaint();
}
in.close();
} catch (Exception e) {
}
pause(100);
}
} catch (Exception e) {
}
}
public void pause(long time) {
try {
Thread.sleep(time);
} catch (Exception e) {
}
}
}
Sending side:
class UpdateScreenThread extends Thread {
Robot robot;
public UpdateScreenThread() {
try {
robot = new Robot();
System.out.println("Update Thread Created");
} catch (Exception e) {
}
}
#Override
public void run() {
System.out.println("Update Thread Running");
Settings.isSharing = true;
Dimension screenSize;
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out;
try {
out = new DataOutputStream(s.getOutputStream());
} catch (Exception e) {
return;
}
while (s.isConnected()) {
//System.out.println("test");
BufferedImage bi = robot.createScreenCapture(screenRectangle);
try {
ImageIO.write(bi, "PNG", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
out.flush();
out.writeInt(bytes.length);
out.flush();
out.write(bytes);
System.out.println("Image sent");
} catch (Exception e) {
}
pause(500);
}
try {
out.close();
} catch (Exception e) {
}
Settings.isSharing = false;
}
}
Thanks to anyone who can help. This is driving me INSANE.
Reduced to the essentials, this is your read loop:
public void run() {
//...
try {
in = new DataInputStream(connection.getInputStream());
while (true) {
//...
try {
int len = in.readInt();
byte[] data = new byte[len];
in.readFully(data, 0, len);
//...
in.close();
} catch (Exception e) {
}
pause(100);
}
} catch (Exception e) {
}
}
Note that the while (true) {...} includes in.close(). Move the close out of the loop.

Java sockets file sending

I am writing Client/Server using java sockets. There is my code:
SERVER:
public void sendFile(File file) {
BufferedOutputStreambufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
int count;
FileInputStream in;
try {
in = new FileInputStream(file);
byte[] mybytearray = new byte[(int) file.length()];
while ((count = in.read(mybytearray)) > 0) {
bufferedOutputStream.write(mybytearray, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CLIENT:
public void downloadFile() {
BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
byte[] aByte = new byte[8192];
int count;
FileOutputStream in;
try {
in = new FileOutputStream("C://fis.txt");
while ((count = bufferedInputStream.read(aByte)) > 0) {
System.out.println(count); // <- nothing happens
in.write(aByte, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Why bufferedInputStream in 2nd function is empty ?
BufferedOutputStream will not write data until the buffer is full. You need to flush the OutputStream:
bufferedOutputStream.flush();

Categories