-4

in the below code i can able to convert a file to gzip but here i am providing the location for input & output staticly. But i need to provide the file name dynamically

example here i am using

String source_filepath = "C:\\Users\\abc\\Desktop\\home6.jpg";
String destinaton_zip_filepath =C:\\Users\\abc\\Desktop\\home6.gzip";

here in place of home6.jpg i can give anything dynamically

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;


public class CompressFileGzip {

    public static void main(String[] args) {

        String source_filepath = "C:\\Users\\abc\\Desktop\\home6.jpg";

        String destinaton_zip_filepath = "C:\\Users\\abc\\Desktop\\home6.gzip";



        CompressFileGzip gZipFile = new CompressFileGzip();

        gZipFile.gzipFile(source_filepath, destinaton_zip_filepath);

    }

    public void gzipFile(String source_filepath, String destinaton_zip_filepath) {

        byte[] buffer = new byte[1024];
        try {    
            FileOutputStream fileOutputStream =new FileOutputStream(destinaton_zip_filepath);

            GZIPOutputStream gzipOuputStream = new GZIPOutputStream(fileOutputStream);

            FileInputStream fileInput = new FileInputStream(source_filepath);

            int bytes_read;

            while ((bytes_read = fileInput.read(buffer)) > 0) {

                gzipOuputStream.write(buffer, 0, bytes_read);

            }

            fileInput.close();

            gzipOuputStream.finish();

            gzipOuputStream.close();

            System.out.println("The file was compressed successfully!");

        } catch (IOException ex) {

            ex.printStackTrace();

        }

    }

}
raghu
  • 19
  • 5
  • The static values are simply variables you have set and passed as parameters to the gzip methods. How would you like to provide a dynamic filename? There are many possibilities available to you, and many APIs that provide the methods to do so. – Finbarr O'B Jul 16 '16 at 08:15
  • `String source_filepath = args[0]` maybe? – Henry Jul 16 '16 at 08:16
  • simply use 7z (7zip has command line interface) –  Jul 16 '16 at 09:10

1 Answers1

0

Just get it from the command line arguments:

public static void main(String[] args) {
    String source_filepath = args[0];
    String destinaton_zip_filepath = args[1];

Note that you'd probably want to add some error checking code here to make sure you actually get two command line arguments, the file exists, etc.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at CompressFileGzip.main(CompressFileGzip.java:20) please help – raghu Jul 18 '16 at 06:44
  • @raghu You need to actually pass the command line arguments – Mureinik Jul 18 '16 at 06:46