前几天一直想做一个程序,保文件或文件夹以及其子目录里的文件打包到压缩文件中,在网上找到了点资料,但不完整,经过调试,终于做出了一个,与大家分享。
package syl.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
/**
* @author SHIYL
*
*/
public class copyAllFileToJar {
public static void main(String args[]) {
String nameOfJar = "D://TEST//2//BATCH.jar";
String nameToAdd = "D://TEST//1";
FileOutputStream jar = null;
File file = new File(nameOfJar);
JarOutputStream newJar = null;
try {
jar = new FileOutputStream(file);
newJar = new JarOutputStream(jar);
File[] addfile = (new File(nameToAdd)).listFiles();
for (File forFile : addfile) {
if (forFile.isFile()) {
writeFile(nameToAdd, newJar, forFile.getName());
} else if (forFile.isDirectory()) {
copyDirectiory(nameToAdd, newJar, forFile.getName());
}
}
} catch (IOException ex) {
System.err.println("Can't access new file");
} finally {
try {
newJar.close();
jar.close();
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
}
public static void copyDirectiory(String nameToAdd, JarOutputStream newJar, String fileName) throws IOException {
File[] file = (new File(nameToAdd + "//" + fileName)).listFiles();
for (File forFile : file) {
if (forFile.isFile()) {
writeFile(nameToAdd, newJar, fileName + "//" + forFile.getName());
} else if (forFile.isDirectory()) {
copyDirectiory(nameToAdd, newJar, fileName + "//" + forFile.getName());
}
}
}
private static void writeFile(String nameToAdd, JarOutputStream newJar,
String fileName) {
byte buffer[] = new byte[4096];
int bytesRead;
File com;
FileInputStream fis = null;
try {
com = new File(nameToAdd + "//" + fileName);
fis = new FileInputStream(com);
JarEntry entry = new JarEntry(fileName);
newJar.putNextEntry(entry);
while ((bytesRead = fis.read(buffer)) != -1) {
newJar.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
System.err.println("writeFile err : " + ex);
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
终于成功了,大家试试吧!!へ_へ