【发布时间】:2016-11-19 10:24:33
【问题描述】:
在下面的代码中,我可以将文件转换为 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]也许? -
简单使用7z(7zip有命令行界面)
标签: java command-line command-line-interface command-line-arguments