How to use PipedInputStream and PipedOutputStream - java

There are many examples of using while converting OutputStream to InputStream.
How could I complete the missing parts below?
I mean putDataOnOutputStream(out) method.
If it is still needed to use ByteArrays, in this case, it doesn't make sense what is the memory advantage of using PipeLines
I need to complete convertToInputStream ;
public static InputStream decrypt(String keyCode, String file) throws IOException, InterruptedException {
OutputStream out;
try {
Cipher cipher = Cipher.getInstance("AES/CBC/Pkcs5Padding");
/****** decyption code
**/
out = new BufferedOutputStream(new FileOutputStream("C:decyrptedText.txt"));
for(int readBytes = in.read(buffer); readBytes>-1; readBytes = in.read(buffer)) {
byte[] decrypted = cipher.update(buffer, 0, readBytes);
out.write(decrypted);
}
byte[] decrypted = cipher.doFinal();
out.write(decrypted);
out.flush();
out.close();
in.close();
} catch (Exception e) {
throw new IllegalStateException(e);
}
return convertToInputStream(out); //
}
public static InputStream convertToInputStream(OutputStream outputStream) throws IOException, InterruptedException {
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
new Thread(
new Runnable(){
public void run(){
//put your code that writes data to the outputstream here.
putDataOnOutputStream(outputStream);
}
}
).start();
//data can be read from the pipedInputStream here.
processDataFromInputStream(in);

Related

Why can't I read an object from a binary file using ObjectInputStream wrapped with a FIleInputStream?

public class JavaApplication {
public static void main(String[] args) throws IOException{
URL u = new URL("https://www.javatpoint.com/java-string-valueof");
byte[]bytes= u.openStream().readAllBytes();
ObjectOutputStream output= new ObjectOutputStream(
new FileOutputStream("binary.dat"));
output.write(bytes);
output.close();
//Scanning the URL works just not the try and catch block
try{
ObjectInputStream input = new ObjectInputStream(new FileInputStream
("binary.dat"));
byte[]byte1= (byte[])input.readObject();
String any;
for(int i=0; i<byte1.length; i++){
any=String.valueOf(byte1[i]);
System.out.println(any);
}
input.close();
}
catch(Exception e){
System.out.println(e);}
}
}
I used a new byte array to read the object from file, use String.valueOf() to obtain the String value of the byte, then a for-loop to iterate the String. What am I doing wrong?
As the first commenter said, your main problem was not using writeObject. The only other problem is the way you turn the bytes into text. Your code will result in the 'ascii' code of the character being printed instead of the character itself. In fact you can simplify the output code as follows:
import java.io.*;
import java.net.*;
public class JavaApplication {
public static void main(String[] args) throws IOException {
URL u = new URL("https://www.javatpoint.com/java-string-valueof");
byte[] bytes = u.openStream().readAllBytes();
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("binary.dat"));
output.writeObject(bytes);
output.close();
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream("binary.dat"));
byte[] byte1 = (byte[]) input.readObject();
System.out.println(new String(byte1));
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
To solve your problem, I prefer you :
Add implementation of URLConnection for avoidance from Http Status 403 / Forbidden. Reference
use ByteArrayOutputStream to write the byte and save it into file using ObjectOutputStream
if you read with readObject() you must write with writeObject()
public class JavaApplication {
public static void main(String[] args) throws IOException, ClassNotFoundException {
URL u = new URL("https://www.javatpoint.com/java-string-valueof");
URLConnection uc = u.openConnection();
uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = uc.getInputStream();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ((n = is.read(byteChunk)) > 0) {
baos.write(byteChunk, 0, n);
}
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s: %s", u.toExternalForm(), e.getMessage());
} finally {
if (is != null) {
is.close();
}
}
byte[] bytes = baos.toByteArray();
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("binary.dat"));
output.writeObject(bytes);
output.close();
//Scanning the URL works just not the try and catch block
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream("binary.dat"));
byte[] byte1 = (byte[]) input.readObject();
String any;
for (int i = 0; i < byte1.length; i++) {
any = String.valueOf(byte1[i]);
System.out.println(any);
}
input.close();
} catch (IOException e) {
System.out.println(e);
}
}
}

ObjectInputStream header problems [duplicate]

I am trying to convert a ArrayList object to a byte string so it can be sent via sockets. When I run this code it converts to a string properly but when I try to convert it back I get the exception "java.io.StreamCorruptedException: invalid stream header: EFBFBDEF". Other answers I looked at on here didn't really help as I am using the matching ObjectOutputStream and ObjectInputStream. Sorry if there is a simple fix as I am new to working with stream objects.
try {
ArrayList<String> text = new ArrayList<>();
text.add("Hello World!");
String byteString = Utils.StringUtils.convertToByteString(text);
ArrayList<String> convertedSet = (ArrayList<String>) Utils.StringUtils.convertFromByteString(byteString);
VCS.getServiceManager().addConsoleLog(convertedSet.get(0));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
public static String convertToByteString(Object object) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(object);
final byte[] byteArray = bos.toByteArray();
return new String(byteArray);
}
}
public static Object convertFromByteString(String byteString) throws IOException, ClassNotFoundException {
final byte[] bytes = byteString.getBytes();
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) {
return in.readObject();
}
}
I figured it out. I had to use Base64 encoding. The conversion methods have to be changed to the following:
public static String convertToByteString(Object object) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(object);
final byte[] byteArray = bos.toByteArray();
return Base64.getEncoder().encodeToString(byteArray);
}
}
public static Object convertFromByteString(String byteString) throws IOException, ClassNotFoundException {
final byte[] bytes = Base64.getDecoder().decode(byteString);
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) {
return in.readObject();
}
}
String is not a container for binary data. You need to pass around the original byte array, or hex- or base64-encode it.
Better still, serialize directly to the socket and get rid of this altogether.

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

Transfer Multiple File problems via socket

Server side:
public class Server
{
public static final String ALGORITHM = "RSA";
public static final String PRIVATE_KEY_FILE = "C:/Users/mrarsenal10/Desktop/server/key/private.key";
public static final String PUBLIC_KEY_FILE = "C:/Users/mrarsenal10/Desktop/server/key/public.key";
public static void generateKey()
{
try
{
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
File privateKeyFile = new File(PRIVATE_KEY_FILE);
File publicKeyFile = new File(PUBLIC_KEY_FILE);
// Create files to store public and private key
if (privateKeyFile.getParentFile() != null) {
privateKeyFile.getParentFile().mkdirs();
}
privateKeyFile.createNewFile();
if (publicKeyFile.getParentFile() != null) {
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();
// Saving the Public key in a file
ObjectOutputStream publicKeyOS = new ObjectOutputStream(
new FileOutputStream(publicKeyFile));
publicKeyOS.writeObject(key.getPublic());
publicKeyOS.close();
// Saving the Private key in a file
ObjectOutputStream privateKeyOS = new ObjectOutputStream(
new FileOutputStream(privateKeyFile));
privateKeyOS.writeObject(key.getPrivate());
privateKeyOS.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
public static boolean areKeysPresent()
{
File privateKey = new File(PRIVATE_KEY_FILE);
File publicKey = new File(PUBLIC_KEY_FILE);
if (privateKey.exists() && publicKey.exists())
{
return true;
}
return false;
}
public static String decrypt(byte[] text, PrivateKey key) { // giải mã
byte[] dectyptedText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// decrypt the text using the private key
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(dectyptedText);
}
static void sendFile(Socket sock, String fName) throws FileNotFoundException, IOException
{
File transferFile = new File (fName);
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length); // luu vao bytearray
OutputStream os = sock.getOutputStream(); // goi outputstream de
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
if (!areKeysPresent()) {
generateKey();
}
ServerSocket serverSocket = new ServerSocket(15124);
Socket sock = serverSocket.accept();
sendFile(sock, PUBLIC_KEY_FILE);
sendFile(sock, "lich.txt");
sock.close();
}
}
Client side:
public class Client
{
public static final String ALGORITHM = "RSA";
public static final String PUBLIC_KEY_FILE = "C:/Users/mrarsenal10/Desktop/Client/public.key";
static void recvFile(Socket sock, String fName) throws FileNotFoundException, IOException
{
int filesize=1022386;
int bytesRead;
int currentTot = 0;
byte [] bytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(fName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
do {
bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead; }
while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
}
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Socket sock = new Socket("127.0.0.1",15124);
recvFile(sock, "public.key");
recvFile(sock, "lich.txt");
sock.close();
}
}
My problem is here i just can send "public.key" or "lich.txt" from server to client, now i want to send both "public.key" and "lich.txt". Thank for your help.
The problem is with the overall design of both the Server and the Client. On the server side it is sending two different files, but on the Client side it is just a stream of data. There is no distinction between one byte representing data from one file vs the next. So what is probably happening is you are calling recvFile, which receives ALL the data from BOTH files sent by the server. After sending the data, the server closes the connection. (You do this explicitly.) So now, on the client side, you have an invalid socket. However, you try to call recvFile again with the socket thinking that represents the second file. This will lead to the SocketException or more likely OutOfBoundsException you are seeing.
To fix this, you need to add more hand-shaking between the Server and Client. The simplest would be a delimiter representing the end of a file. A better approach would be to append a known-size header to the front of every "message" (aka file) before sending any data which lets the client know the size of the file. Then once the client receives the header it knows exactly how many bytes to read.
For now, to prevent the crash change you're recvFile method to something like this:
byte[] bytearray = new byte[4096];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(fName);
int bytesRead;
while ((bytesRead = is.read(bytearray)) >= 0) {
if (bytesRead > 0) {
fos.write(bytearray, 0, bytesRead);
}
}
fos.flush();
fos.close();

GZIP compression to a byte array

I am trying to write a class that can compress data. The below code fails (no exception is thrown, but the target .gz file is empty.)
Besides: I don't want to generate the .gz file directly like it is done in all examples. I only want to get the compressed
data, so that I can e.g. encrypt it before writting the data to a file.
If I write directly to a file everything works fine:
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
GZIPOutputStream zipStream = null;
FileOutputStream fileStream = null;
try
{
fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
zipStream = new GZIPOutputStream(fileStream);
zipStream.write(dataToCompress);
fileStream.write(compressedData);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try{ zipStream.close(); }
catch(Exception e){ }
try{ fileStream.close(); }
catch(Exception e){ }
}
}
}
But, if I want to 'bypass' it to the byte array stream it does not produce a single byte - compressedData is always empty.
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
byte[] compressedData = null;
GZIPOutputStream zipStream = null;
ByteArrayOutputStream byteStream = null;
FileOutputStream fileStream = null;
try
{
byteStream = new ByteArrayOutputStream(dataToCompress.length);
zipStream = new GZIPOutputStream(byteStream);
zipStream.write(dataToCompress);
compressedData = byteStream.toByteArray();
fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
fileStream.write(compressedData);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try{ zipStream.close(); }
catch(Exception e){ }
try{ byteStream.close(); }
catch(Exception e){ }
try{ fileStream.close(); }
catch(Exception e){ }
}
}
}
The problem is that you are not closing the GZIPOutputStream. Until you close it the output will be incomplete.
You just need to close it before reading the byte array. You need to reorder the finally blocks to achieve this.
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
try
{
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(dataToCompress.length);
try
{
GZIPOutputStream zipStream =
new GZIPOutputStream(byteStream);
try
{
zipStream.write(dataToCompress);
}
finally
{
zipStream.close();
}
}
finally
{
byteStream.close();
}
byte[] compressedData = byteStream.toByteArray();
FileOutputStream fileStream =
new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
try
{
fileStream.write(compressedData);
}
finally
{
try{ fileStream.close(); }
catch(Exception e){ /* We should probably delete the file now? */ }
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I do not recommend inititalizing the stream variables to null, because it means your finally block can also throw a NullPointerException.
Also note that you can declare main to throw IOException (then you would not need the outermost try statement.)
There is little point in swallowing exceptions from zipStream.close();, because if it throws an exception you will not have a valid .gz file (so you should not proceed to write it.)
Also I would not swallow exceptions from byteStream.close(); but for a different reason - they should never be thrown (i.e. there is a bug in your JRE and you would want to know about that.)
I've improved JITHINRAJ's code - used try-with-resources:
private static byte[] gzipCompress(byte[] uncompressedData) {
byte[] result = new byte[]{};
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);
GZIPOutputStream gzipOS = new GZIPOutputStream(bos)) {
gzipOS.write(uncompressedData);
// You need to close it before using bos
gzipOS.close();
result = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static byte[] gzipUncompress(byte[] compressedData) {
byte[] result = new byte[]{};
try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPInputStream gzipIS = new GZIPInputStream(bis)) {
byte[] buffer = new byte[1024];
int len;
while ((len = gzipIS.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
result = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you are still looking an answer you can use the below code to get the compressed byte[] using deflater and decompress it using inflater.
public static void main(String[] args) {
//Some string for testing
String sr = new String("fsdfesfsfdddddddsfdsfssdfdsfdsfdsfdsfdsdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghghghghggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggfsdfesfsfdddddddsfdsfssdfdsfdsfdsfdsfdsdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghghghghggggggggggggggggggggggggggggggggggggggggg");
byte[] data = sr.getBytes();
System.out.println("src size "+data.length);
try {
compress(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] compress(byte[] data) throws IOException {
Deflater deflater = new Deflater();
deflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
deflater.finish();
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
System.out.println("Original: " + data.length );
System.out.println("Compressed: " + output.length );
return output;
}
To compress
private static byte[] compress(byte[] uncompressedData) {
ByteArrayOutputStream bos = null;
GZIPOutputStream gzipOS = null;
try {
bos = new ByteArrayOutputStream(uncompressedData.length);
gzipOS = new GZIPOutputStream(bos);
gzipOS.write(uncompressedData);
gzipOS.close();
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
assert gzipOS != null;
gzipOS.close();
bos.close();
}
catch (Exception ignored) {
}
}
return new byte[]{};
}
To uncompress
private byte[] uncompress(byte[] compressedData) {
ByteArrayInputStream bis = null;
ByteArrayOutputStream bos = null;
GZIPInputStream gzipIS = null;
try {
bis = new ByteArrayInputStream(compressedData);
bos = new ByteArrayOutputStream();
gzipIS = new GZIPInputStream(bis);
byte[] buffer = new byte[1024];
int len;
while((len = gzipIS.read(buffer)) != -1){
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
assert gzipIS != null;
gzipIS.close();
bos.close();
bis.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
return new byte[]{};
}
You can use the below function, it is tested and working fine.
In general, your code has serious problem of ignoring the exceptions! returning null or simply not printing anything in the catch block will make it very difficult to debug
You do not have to write the zip output to a file if you want to process it further (e.g. encrypt it), you can easily modify the code to write the output to in-memory stream
public static String zip(File inFile, File zipFile) throws IOException {
FileInputStream fis = new FileInputStream(inFile);
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fos);
try {
zout.putNextEntry(new ZipEntry(inFile.getName()));
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = fis.read(buffer)) > 0) {
zout.write(buffer, 0, len);
}
zout.closeEntry();
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
try{zout.close();}catch(Exception ex){ex.printStackTrace();}
try{fis.close();}catch(Exception ex){ex.printStackTrace();}
}
return zipFile.getAbsolutePath();
}
Most of the examples have wrong exception handling.
public static byte[] gzipBytes(byte[] payload) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(baos)) {
gzip.write(payload);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
// note: toByteArray should be called after try-with-resources, not inside
return baos.toByteArray();
}
public static byte[] gunzipBytes(byte[] gzPayload) {
ByteArrayInputStream bais = new ByteArrayInputStream(gzPayload);
try (GZIPInputStream gzip = new GZIPInputStream(bais)) {
// java 9+ required for this method
return gzip.readAllBytes();
} catch (IOException e) {
throw new UncheckedIOException("Error while unpacking gzip content", e);
}
}
Try with this code..
try {
String inputFileName = "test.txt"; //may use your file_Path
String zipFileName = "compressed.zip";
//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
outStream.closeEntry();
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Also may be helpful this one..
http://www.java-samples.com/java/zip_files_in_a_folder_using_java.htm

Categories

Resources