0

I'm using TrueZip to create archives. It seems it regards the path D:\ as a system root folder and prevents me from creating files there. My os and all programs are as per default located at C:. The drive D:\ contains personal data (documents, pictures, videos, whatever).

How can I create archives at the root of my drive?

The code I'm using to create archives:

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);
    }
}

The error message I'm getting:

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
fukiburi
  • 615
  • 1
  • 7
  • 24

1 Answers1

1

I will try to answer you using zip4j_1.3.2 instead library TrueZIP because there is not any issue with the Zip library but with file handling.

FilesZipperExample

Try to understand through following example, and you can change source as per of your requirement:

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();
        }
    }
}
ArifMustafa
  • 4,617
  • 5
  • 40
  • 48