public class foldertoZip {
List<String> fileList;
private static final String OUTPUT_ZIP_FILE = "Folder.zip";
private static final String SOURCE_FOLDER = "C:\\Users\\wahidbasha\\Documents\\NetBeansProjects\\EpubtoZip\\build\\web\\2012LH"; //SourceFolder path
zipFIle() {
fileList = new ArrayList<String>();
}
public static void main(String[] args) {
zipFIle appZip = new zipFIle();
appZip.generateFileList(new File(SOURCE_FOLDER));
appZip.zipIt(OUTPUT_ZIP_FILE);
}
public void zipIt(String zipFile) {
byte[] buffer = new byte[1024];
String source = "";
try {
try {
source = SOURCE_FOLDER.substring(SOURCE_FOLDER.lastIndexOf("\\") + 1, SOURCE_FOLDER.length());
} catch (Exception e) {
source = SOURCE_FOLDER;
}
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
for (String file : this.fileList) {
System.out.println("File Added : " + file);
ZipEntry ze = new ZipEntry(source + File.separator + file);
zos.putNextEntry(ze);
FileInputStream in =
new FileInputStream(SOURCE_FOLDER + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
//remember close it
zos.close();
System.out.println("Folder successfully compressed");
} catch (IOException ex) {
}
}
public void generateFileList(File node) {
//add file only
if (node.isFile()) {
fileList.add(generateZipEntry(node.toString()));
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename : subNote) {
generateFileList(new File(node, filename));
}
}
}
private String generateZipEntry(String file) {
return file.substring(SOURCE_FOLDER.length() + 1, file.length());
}
}
这里我将2012LH的所有文件夹(包含多个文件夹(例如A,B,C)和A,B,C内的文件(如a,b,c,d,e))转换为zip文件夹,即,Folder.zip;但是它在zipFIle()上显示无效的方法声明,任何正文都可以帮助我如何做到这一点,提前谢谢。
答案 0 :(得分:0)
我假设你想要一个构造函数。您必须将类名与构造函数名称匹配:
public foldertoZip() {
fileList = new ArrayList<String>();
}
public static void main(String[] args) {
foldertoZip appZip = new foldertoZip();
appZip.generateFileList(new File(SOURCE_FOLDER));
appZip.zipIt(OUTPUT_ZIP_FILE);
}
无论如何,我建议你下次用大写字母命名类(例如FolderToZipProcessor
)。
答案 1 :(得分:0)
看起来“public class foldertoZip”需要更改为“public class zipFIle”,并且应该允许zipFIle()方法作为构造函数,它应该会很好。