在下面的代碼中,我可以將文件轉換爲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();
}
}
}
靜態值只是你設置的變量,並作爲參數傳遞給gzip方法。你想如何提供動態文件名?有很多可用的可能性,以及提供這些方法的許多API。 –
'String source_filepath = args [0]'也許? – Henry
只需使用7z(7zip有命令行界面) –