如何在" D:\"中创建TrueZip存档?

时间:2018-01-17 15:08:03

标签: java swing filenotfoundexception truezip

我使用TrueZip创建档案。它似乎将路径D:\视为系统根文件夹,并阻止我在那里创建文件。我的操作系统和所有程序默认位于C:。驱动器D:\包含个人数据(文档,图片,视频等)。

如何在驱动器的根目录下创建存档?

我用来创建档案的代码:

import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileOutputStream;
import de.schlichtherle.truezip.zip.ZipEntry;
import de.schlichtherle.truezip.zip.ZipOutputStream;

import javax.swing.*;
import java.io.*;

public class MainClass {
    public static void main(String[] args) throws IOException {
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("Please select the target folder.");
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        JFrame applicationFrame = new JFrame();
        if (chooser.showSaveDialog(applicationFrame) != JFileChooser.APPROVE_OPTION)
            return;
        File selectedFile = chooser.getSelectedFile();

        TFile archiveFile = new TFile(selectedFile + ".zip");
        System.out.println("Selected file: " + archiveFile.getAbsolutePath());
        ZipOutputStream zipOutputStream = new ZipOutputStream(new TFileOutputStream(archiveFile));

        File folderToZip = new File("D:/filesToZip");
        File[] files = folderToZip.listFiles();

        for (File file : files) {

            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            int avail = bis.available();
            byte[] buffer = new byte[avail];
            if (avail > 0) {
                bis.read(buffer, 0, avail);
            }
            bis.close();

            ZipEntry zipEntry = new ZipEntry(file.getName());
            zipOutputStream.putNextEntry(zipEntry);
            zipOutputStream.write(buffer, 0, buffer.length);
            zipOutputStream.closeEntry();
        }

        zipOutputStream.close();

        System.exit(0);
    }
}

我收到的错误消息:

Selected file: D:\test.zip
Exception in thread "main" java.io.FileNotFoundException: D:\test.zip
    at de.schlichtherle.truezip.file.TFileOutputStream.newOutputStream(TFileOutputStream.java:147)
    at de.schlichtherle.truezip.file.TFileOutputStream.<init>(TFileOutputStream.java:116)
    at MainClass.main(MainClass.java:21)
Caused by: de.schlichtherle.truezip.fs.FsArchiveFileSystemException: <file system root> (only files can get replaced)
    at de.schlichtherle.truezip.fs.FsArchiveFileSystem.mknod(FsArchiveFileSystem.java:379)
    at de.schlichtherle.truezip.fs.FsBasicArchiveController$1Output.mknod(FsBasicArchiveController.java:273)
    at de.schlichtherle.truezip.fs.FsBasicArchiveController$1Output.newOutputStream(FsBasicArchiveController.java:233)
    at de.schlichtherle.truezip.fs.FsContextController$Output.newOutputStream(FsContextController.java:322)
    at de.schlichtherle.truezip.fs.FsResourceController$Output.newOutputStream(FsResourceController.java:283)
    at de.schlichtherle.truezip.socket.DelegatingOutputSocket.newOutputStream(DelegatingOutputSocket.java:57)
    at de.schlichtherle.truezip.fs.FsSyncController$Output.newOutputStream(FsSyncController.java:454)
    at de.schlichtherle.truezip.fs.FsLockController$Output$1NewOutputStream.call(FsLockController.java:509)
    at de.schlichtherle.truezip.fs.FsLockController$Output$1NewOutputStream.call(FsLockController.java:506)
    at de.schlichtherle.truezip.fs.FsLockController.locked(FsLockController.java:328)
    at de.schlichtherle.truezip.fs.FsLockController.writeLocked(FsLockController.java:268)
    at de.schlichtherle.truezip.fs.FsLockController$Output.newOutputStream(FsLockController.java:513)
    at de.schlichtherle.truezip.fs.FsFinalizeController$Output.newOutputStream(FsFinalizeController.java:209)
    at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Output$NewOutputStream.call(FsFalsePositiveArchiveController.java:409)
    at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Output$NewOutputStream.call(FsFalsePositiveArchiveController.java:402)
    at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$TryChild.call(FsFalsePositiveArchiveController.java:507)
    at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController.call(FsFalsePositiveArchiveController.java:104)
    at de.schlichtherle.truezip.fs.FsFalsePositiveArchiveController$1Output.newOutputStream(FsFalsePositiveArchiveController.java:399)
    at de.schlichtherle.truezip.file.TFileOutputStream.newOutputStream(TFileOutputStream.java:143)
    ... 2 more

1 个答案:

答案 0 :(得分:0)

我会尝试使用zip4j_1.3.2而不是库TrueZIP来回答您,因为Zip库没有任何问题,但文件处理

FilesZipperExample

尝试通过以下示例了解,您可以根据您的要求更改来源:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

public class FilesZipperExample {

    private static JFrame frame;
    private static JList<String> list;
    private static DefaultListModel<String> listModel;
    private static JFileChooser input;
    private static File[] choosedFiles = null;

    public static void main(String[] args) {
        //Not handling Native OS Look
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                runFileZipperApp();
            }
        });
    }

    private static void runFileZipperApp() {
        frame = new JFrame();
        frame.setTitle("Files Zip Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(2, 1));
        frame.setBounds(400, 250, 300, 200);

        JButton button = new JButton("Choose Files...");
        frame.add(button);

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                chooseFiles();
            }
        });

        listModel = new DefaultListModel<String>();
        listModel.addElement("Nothing...");

        list = new JList<String>(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        frame.add(list);

        frame.setVisible(true);
    }

    private static void chooseFiles() {
        // Using Windows 8.1 OS
        //FileChooser to get zip inside
        input = new JFileChooser(System.getProperty("user.home"));
        input.setFileSelectionMode(JFileChooser.FILES_ONLY);
        input.setAcceptAllFileFilterUsed(false);
        input.setControlButtonsAreShown(true);
        input.setMultiSelectionEnabled(true);
        input.setFileHidingEnabled(true);
        input.setDialogTitle("Add Files like Documents, Music, Video & many more!...");

        int result = input.showOpenDialog(frame);

        //FileChooser Approved after Multi Files Selection
        if (result == JFileChooser.APPROVE_OPTION) {

            //getting multiple selected files
            choosedFiles = input.getSelectedFiles();

            //putting the files path in JList
            listModel.clear();
            for (File file : choosedFiles) {
                String path = file.getAbsolutePath().replaceAll("\\\\", "/");
                listModel.addElement(path);
            }
            list.setModel(listModel);

            //Select Zip File Location and File Name to save there
            JFileChooser output = new JFileChooser(System.getProperty("user.home"));
            output.setFileSelectionMode(JFileChooser.FILES_ONLY);
            output.setControlButtonsAreShown(true);
            output.setMultiSelectionEnabled(false);
            output.setFileHidingEnabled(true);
            output.setDialogTitle("Select directory location and enter zip name");

            //YOUR PROBLEM IS AROUND HERE WITHIN 3 LINES
            File tempFile = new File("test.zip");
            output.setSelectedFile(tempFile);
            String targetZipped = null;

            // you can change the zip file name there and
            // mentioning extension .zip is not mandatory
            result = output.showSaveDialog(frame);

            if (result == JFileChooser.APPROVE_OPTION) {
                targetZipped = output.getCurrentDirectory().getPath() + 
                                                "\\" + tempFile.getName();

                System.out.println(targetZipped);
                Compressor.zip(choosedFiles, targetZipped);
            }
        }
    }
}

class Compressor {

    //Capable to zip file sizes beyond JVM Memory, and Tested.
    static void zip(File[] folder, String destinationFilePath) {
        try {
            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_FASTEST);

            ZipFile zipFile = new ZipFile(destinationFilePath);

            for (File targetFile : folder) {
                if (targetFile.isFile())
                    zipFile.addFile(targetFile, parameters);
                else if (targetFile.isDirectory())
                    zipFile.addFolder(targetFile, parameters);
            }

        } catch (net.lingala.zip4j.exception.ZipException ze) {
            ze.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    static void unzip(final String targetZipFilePath, final String destinationFolderPath) {
        try {
            ZipFile zipFile = new ZipFile(targetZipFilePath);
            zipFile.extractAll(destinationFolderPath);
        } catch (net.lingala.zip4j.exception.ZipException ze) {
            ze.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}