java操作文件類 (文件解壓縮 文件增刪改查)
import java.io.File;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
壓縮,解壓,刪除,拷貝操作。
注意:此類中用到的壓縮類ZipEntry等都來自于org.apache.tools包而非java.util。此包在ant.jar中有。 *
- @author Tony */
public class FileUtil {
protected static Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
*
* 壓縮文件
*
* @param inputFileName
* 要壓縮的文件或文件夾路徑,例如:c:\\a.txt,c:\\a\
*
* @param outputFileName
* 輸出zip文件的路徑,例如:c:\\a.zip
*
*/
public static void zip(String inputFileName, String outputFileName)
throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
outputFileName));
zip(out, new File(inputFileName), "");
log.debug("壓縮完成!");
out.closeEntry();
out.close();
}
/**
*
* 壓縮文件
*
* @param out
* org.apache.tools.zip.ZipOutputStream
*
* @param file
* 待壓縮的文件
*
* @param base
* 壓縮的根目錄
*
*/
private static void zip(ZipOutputStream out, File file, String base)
throws Exception {
if (file.isDirectory()) {
File[] fl = file.listFiles();
base = base.length() == 0 ? "" : base + File.separator;
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new ZipEntry(base));
log.debug("添加壓縮文件:" + base);
FileInputStream in = new FileInputStream(file);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
/**
*
* 解壓zip文件
*
* @param zipFileName
* 待解壓的zip文件路徑,例如:c:\\a.zip
*
* @param outputDirectory
* 解壓目標文件夾,例如:c:\\a\
*
*/
public static void unZip(String zipFileName, String outputDirectory)
throws Exception {
ZipFile zipFile = new ZipFile(zipFileName);
try {
Enumeration<?> e = zipFile.getEntries();
ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
while (e.hasMoreElements()) {
zipEntry = (ZipEntry) e.nextElement();
log.debug("解壓:" + zipEntry.getName());
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
f.mkdir();
log
.debug("創建目錄:" + outputDirectory + File.separator
+ name);
} else {
String fileName = zipEntry.getName();
fileName = fileName.replace('\\', '/');
if (fileName.indexOf("/") != -1) {
createDirectory(outputDirectory, fileName.substring(0,
fileName.lastIndexOf("/")));
fileName = fileName.substring(
fileName.lastIndexOf("/") + 1, fileName
.length());
}
File f = new File(outputDirectory + File.separator
+ zipEntry.getName());
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
in.close();
out.close();
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
zipFile.close();
log.debug("解壓完成!");
}
}
/**
* 功能描述:列出某文件夾及其子文件夾下面的文件,并可根據擴展名過濾
*
* @param path
* 文件
*/
public static void list(File path) {
if (!path.exists()) {
System.out.println("文件名稱不存?");
} else {
if (path.isFile()) {
if (path.getName().toLowerCase().endsWith(".pdf")
|| path.getName().toLowerCase().endsWith(".doc")
|| path.getName().toLowerCase().endsWith(".chm")
|| path.getName().toLowerCase().endsWith(".html")
|| path.getName().toLowerCase().endsWith(".htm")) {// 文件格式
System.out.println(path);
System.out.println(path.getName());
}
} else {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
list(files[i]);
}
}
}
}
/**
*
* @param directory
* @param subDirectory
*/
private static void createDirectory(String directory, String subDirectory) {
String dir[];
File fl = new File(directory);
try {
if (subDirectory == "" && fl.exists() != true) {
fl.mkdir();
} else if (subDirectory != "") {
dir = subDirectory.replace('\\', '/').split("/");
for (int i = 0; i < dir.length; i++) {
File subFile = new File(directory + File.separator + dir[i]);
if (subFile.exists() == false)
subFile.mkdir();
directory += File.separator + dir[i];
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
/**
*
* 拷貝文件夾中的所有文件到另外一個文件夾
*
* @param srcDirector
* 源文件夾
*
* @param desDirector
* 目標文件夾
*
*/
public static void copyFileWithDirector(String srcDirector,
String desDirector) throws IOException {
(new File(desDirector)).mkdirs();
File[] file = (new File(srcDirector)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
log.debug("拷貝:" + file[i].getAbsolutePath() + "-->"
+ desDirector + "/" + file[i].getName());
FileInputStream input = new FileInputStream(file[i]);
FileOutputStream output = new FileOutputStream(desDirector
+ "/" + file[i].getName());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (file[i].isDirectory()) {
log.debug("拷貝:" + file[i].getAbsolutePath() + "-->"
+ desDirector + "/" + file[i].getName());
copyFileWithDirector(srcDirector + "/" + file[i].getName(),
desDirector + "/" + file[i].getName());
}
}
}
/**
*
* 刪除文件夾
*
* @param folderPath
* folderPath 文件夾完整絕對路徑
*
*/
public static void delFolder(String folderPath) throws Exception {
// 刪除完里面所有內容
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
// 刪除空文件夾
myFilePath.delete();
}
/**
*
* 刪除指定文件夾下所有文件
*
* @param path
* 文件夾完整絕對路徑
*
*/
public static boolean delAllFile(String path) throws Exception {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
// 先刪除文件夾里面的文件
delAllFile(path + "/" + tempList[i]);
// 再刪除空文件夾
delFolder(path + "/" + tempList[i]);
flag = true;
}
}
return flag;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("H:\\");
list(file);
}
}</pre>
本文由用戶 ye34 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!