-4

在下面的代码中,我可以将文件转换为gzip,但在此我提供静态输入&输出的位置。但我需要在这里提供的文件名动态如何压缩GZip格式的文件?

例如我用

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

这里到位home6.jpg的,我可以付出一切动态

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

     } 

    } 

} 
+0

静态值只是你设置的变量,并作为参数传递给gzip方法。你想如何提供动态文件名?有很多可用的可能性,以及提供这些方法的许多API。 –

+0

'String source_filepath = args [0]'也许? – Henry

+0

只需使用7z(7zip有命令行界面) –

回答

0

从命令刚刚得到它线参数:

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

请注意,你可能想添加一些错误检查鳕鱼在这里确保你实际上得到了两个命令行参数,文件存在等。

+0

异常在线程“主”java.lang.ArrayIndexOutOfBoundsException:0 \t at CompressFileGzip.main(CompressFileGzip.java:20)请帮忙 – raghu

+0

@raghu您需要实际传递命令线参数 – Mureinik