我開發了一個程序,我想將不同的文件保存爲zip作爲備份,然後在單擊還原按鈕時加載它們。我有下面的保存文件代碼,但如何使用JFileChooser加載此文件?我不需要將它讀入程序,只需將它解壓縮到我的應用程序所在的文件夾中即可。我將如何做到這一點?我創建zip代碼如下:使用JFileChooser加載並讀取zip文件?
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,以節省升值?
編輯:多虧了用戶184994.這是我完成的文件輸入代碼:
public class ZipInput {
public void loadZip() {
// 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);
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter());
int response = fc.showOpenDialog(null);
// Check the user pressed OK, and not Cancel.
if (response == JFileChooser.APPROVE_OPTION) {
File backUp = fc.getSelectedFile();
byte[] buffer = new byte[1024];
try {
//get the zip file content
ZipInputStream zis = new ZipInputStream(new FileInputStream(backUp));
//get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(fileName);
System.out.println("file unzip : " + newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
//new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
問:爲什麼不把「Backups.zip」變成一個方法參數,然後從JFileChooser處理程序中調用createZip(使用新參數)? – FoggyDay
嗯從來沒有想過的感謝! – eoinDub