【发布时间】:2018-04-29 23:32:51
【问题描述】:
我正在尝试在 Java 中生成一个 zip 文件,其中包含位于不同位置的多个不同类型的文件(例如图像、字体等)。此外,我希望 zip 文件具有按类型放置文件的子文件夹(例如,图像应该转到 zip 中的图像文件夹。
这些是我拥有的文件(每个文件可以在不同的位置):
- index.html
- img1.jpg
- img2.jpg
- font1.woff
- font2.woff
- style.css
- custom.js
这就是它们在 zip 文件中的样子:
- index.html
- images/img1.jpg
- images/img2.jpg
- 字体/font1.woff
- 字体/font2.woff
- js/custom.js
- css/styles.css
到目前为止,我已经设法在特定路径中获取一个文件并提示用户输入输出位置。将使用输入中指定的文件生成一个 zip 文件。这是我到目前为止的代码:
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Speicherort auswählen");
int userSelection = fileChooser.showSaveDialog(parentFrame);
String pathToFile;
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
print(fileToSave.getAbsolutePath());
pathToFile = fileToSave.getAbsolutePath();
}
pathToFile = pathToFile.replace("\\", "/");
String outFileName = pathToFile;
String inFileName = "C:/Users/asoares/Desktop/mobio_export_test/index.html";
ZipOutputStream zos = null;
FileInputStream fis = null;
try {
zos = new ZipOutputStream(new FileOutputStream(outFileName));
fis = new FileInputStream(inFileName);
zos.putNextEntry(new ZipEntry(new File(inFileName).getName()));
int len;
byte[] buffer = new byte[2048];
while((len = fis.read(buffer, 0, buffer.length)) > 0) {
zos.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {}
}
if(zos != null){
try {
zos.closeEntry();
zos.close();
} catch (IOException e) {}
}
}
如果有人可以帮助我,我会很高兴!!!
【问题讨论】:
标签: java zip subdirectory