In my application I want to zip a file or folder from a given userinput. When I try to get the input from a JDialog, thats working fine but if I want to try to let the user choose from a fileChooser, my programm wont work - its always creating an empty zip file. Please can you teach me how to fix that?
EDIT: When I try to get filename and outputname by JDialog, thats working fine but when I want to pick the filename by a filechooser I can't pass it to my further functions the correct way. Maybe it could be because the directory separator? It writes the filename and also the filepath but when I pass it it wont work.
import java.io.*;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.JFileChooser;
public class Zipper {
int prefixLength;
ZipOutputStream zipOut;
byte[] ioBuffer = new byte[4096];
public Zipper(String dirFileName, String dirFileOutput) throws Exception
{ prefixLength = dirFileName.lastIndexOf("/") + 1;
zipOut = new ZipOutputStream(new FileOutputStream("./" + dirFileOutput + ".zip"));
createZipFrom(new File(dirFileName));
zipOut.close();
}
void createZipFrom(File dir) throws Exception
{ if (dir.exists() && dir.canRead() && dir.isDirectory())
{ File[] files = dir.listFiles();
if (files != null)
{ for (File file: files)
{ if (file.isDirectory())
{ createZipFrom(file);
}
else
{ String filePath = file.getPath();//.replace('\\', '/');
FileInputStream in = new FileInputStream(filePath);
zipOut.putNextEntry(new ZipEntry(filePath.substring(prefixLength)));
int bytesRead;
while ((bytesRead = in.read(ioBuffer)) > 0)
{ zipOut.write(ioBuffer, 0, bytesRead);
}
System.out.println(filePath + " added\n");
zipOut.closeEntry();
in.close();
}
}
}
}
}
public static void main(String[] args) throws Exception {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getPath());
String dirFileName = selectedFile.getPath(); // should come from the fileChooser but isnt working
String dirFileOutput = JOptionPane.showInputDialog(null, "packetname"); // thats working..
System.out.println(dirFileName);
System.out.println(dirFileOutput);
new Zipper(dirFileName, dirFileOutput);
System.out.println("package " + dirFileOutput + "." + ".zip created\n");
}
}
EDIT: I got it running with changing
prefixLength = dirFileName.lastIndexOf("/") + 1;
to this
prefixLength = dirFileName.lastIndexOf("\\") + 1;