Example to decompress multi files from .zip using java.util.zip, with JavaFX UI.
|
Decompress files from .zip using java.util.zip |
package javafx_zip;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFX_Zip extends Application {
File fileSrc;
private static final int bufferSize = 8192;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
final Label labelFile = new Label();
Button btn = new Button();
btn.setText("Open FileChooser'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("Zip files (*.zip)", "*.zip");
fileChooser.getExtensionFilters().add(extFilter);
File fileSrc = fileChooser.showOpenDialog(null);
String source = fileSrc.getPath();
String targetUnZipPath = fileSrc.getParent();
try {
//Compress file
FileInputStream fileInputStream =
new FileInputStream(source);
BufferedInputStream bufferedInputStream =
new BufferedInputStream(fileInputStream);
ZipInputStream zipInputStream =
new ZipInputStream(bufferedInputStream);
ZipEntry zipEntry;
String unzippedMsg = "";
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
try {
byte[] buffer = new byte[bufferSize];
String unzippedFile = targetUnZipPath + "/" + zipEntry.getName();
FileOutputStream fileOutputStream =
new FileOutputStream(unzippedFile);
int size;
while ((size = zipInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, size);
}
fileOutputStream.flush();
fileOutputStream.close();
unzippedMsg += unzippedFile + "\n";
} catch (Exception ex) {
}
}
zipInputStream.close();
labelFile.setText("Unzipped files: \n" + unzippedMsg);
} catch (IOException ex) {
Logger.getLogger(JavaFX_Zip.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
VBox vBox = new VBox();
vBox.getChildren().addAll(btn, labelFile);
StackPane root = new StackPane();
root.getChildren().add(vBox);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
No comments:
Post a Comment