我开发了一个程序,我希望将不同的文件保存为 zip 作为备份,然后在单击还原按钮时将其加载回来。我有下面的保存文件代码但是如何使用JFileChooser
加载此文件?我不需要将它读取到程序中,只需将其解压缩到我的应用程序所在的文件夹中即可。我该怎么做?我的创建邮政编码如下:
public void createZip(){
byte[] buffer = new byte[1024];
String[] srcFiles = {"Payments.dat", "PaymentsPosted.dat", "Receipts.dat", "ReceiptsPosted.dat", "AccountDetails.dat", "AssetsLiabilities.dat", "UnitDetails.dat"};
String zipFile = "Backups.zip";
try{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (int i=0; i < srcFiles.length; i++) {
File srcFile = new File(srcFiles[i]);
FileInputStream fis = new FileInputStream(srcFile);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
}catch(IOException ex){
ex.printStackTrace();
}
JOptionPane.showMessageDialog(null,"File Saved! See Backups.zip in your program folder");
}
}
如果有人能告诉我如何将上述方法包装到JFileChooser
中以保存,我还是很感激。
答案 0 :(得分:2)
要创建JFileChooser,代码如下所示:
public void showOpenDialog() {
// Create a filter so that we only see .zip files
FileFilter filter = new FileNameExtensionFilter(null, "zip");
// Create and show the file filter
JFileChooser fc = new JFileChooser();
fc.setFileFilter(filter);
int response = fc.showOpenDialog(null);
// Check the user pressed OK, and not Cancel.
if (response == JFileChooser.APPROVE_OPTION) {
File yourZip = fc.getSelectedFile();
// Do whatever you want with the file
// ...
}
}
就实际解压缩压缩文件而言,您可以找到更多信息here。