import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
public class FileUtil {
private static final int MAX_FILE_NUM_PER_DIR = 500;
private static final int MAX_DIR_NUM = 200;
private static final String TAG = LogTag.TAG_UTIL;
public static void delAutoChangeMusicList(List<AudioInfo> miList, String logTag) {
if (miList == null || miList.size() == 0) {
return;
}
try {
int miSize = miList.size();
for (int i = 0; i < miSize; i++) {
AudioInfo mi = miList.get(i);
String md5 = mi.getMd5();
String path = mi.getFilePath();
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
} catch (Exception ex) {
if (MyLog.isDyeLevel()) {
MyLog.log(logTag, MyLog.DYE_LOG_LEVEL, "del AutoChangeMusicList fail", ex);
}
}
}
public static StorageInfo getAvailableVolumeByNeedSpace(long needSpace) {
StorageVolume[] volumeArray = getVolumeList();
StorageInfo firstSecondSI = null;
long MIN_SIZE = 200 * 1024 * 1024L;
for (int i = 0; i < volumeArray.length; i++) {
StorageVolume vol = volumeArray[i];
if (vol.isPrimary()) {
StatFs loopStatFs = new StatFs(vol.getPath());
long restSpace = loopStatFs.getAvailableBytes() - needSpace;
if (restSpace > MIN_SIZE) {
StorageInfo si = new StorageInfo();
si.setStorageFlag(StorageInfo.PRIMARY_STORAGE_VOLUME);
si.setRootPath(vol.getPath());
return si;
}
} else {
if (firstSecondSI == null) {
StatFs loopStatFs = new StatFs(vol.getPath());
long restSpace = loopStatFs.getAvailableBytes() - needSpace;
if (restSpace > MIN_SIZE) {
StorageInfo si = new StorageInfo();
si.setStorageFlag(vol.getPath());
si.setRootPath(vol.getPath());
firstSecondSI = si;
}
} else {
// already find
}
}
}
return firstSecondSI;
}
public static String[] getAllMusicDir() {
StorageVolume[] volumeArray = getVolumeList();
ArrayList<String> musicDirList = new ArrayList<String>();
for (int i = 0; i < volumeArray.length; i++) {
StorageVolume vol = volumeArray[i];
String musicDir = getRootMusicDirByRootPath(vol.getPath());
File file = new File(musicDir);
if (file.exists()) {
musicDirList.add(file.getAbsolutePath());
}
}
return musicDirList.toArray(new String[musicDirList.size()]);
}
public static String getHandDownloadMusicDir() {
return Environment.getExternalStorageDirectory().getPath() + CenterConstants.DISK_HAND_MUSIC_PATH;
}
private static String getRootMusicDirByRootPath(String rootPath) {
return rootPath + CenterConstants.DISK_ROOT_MUSIC_PATH;
}
public static String getCommonMusicDirByRootPath(String rootPath) {
return rootPath + CenterConstants.DISK_COMMON_MUSIC_PATH;
}
public static String getChangeMusicDir(String rootPath, long userId) {
return rootPath + CenterConstants.DISK_CHANGE_MUSIC_PATH + userId + "/";
}
public static String getChangeMusicPath(String rootPath, long userId, long listVer, ChangeMusicFileInfo cmfi) {
String dir = rootPath + CenterConstants.DISK_CHANGE_MUSIC_PATH + userId + "/" + listVer + "/";
String fileName = CenterMediaServer.genFileNameByMd5(dir, cmfi.getSongName(), cmfi.getMd5());
String path = dir + fileName;
return path;
}
public synchronized static String genMusicDir(Context ctx, String rootDirStr) {
// SharedPreferences appSp =
// ctx.getSharedPreferences(CenterPrefConstants.COMM_SP_NAME,
// Context.MODE_PRIVATE);
// String latestMusicDir =
// appSp.getString(CenterPrefConstants.LATEST_MUSIC_DIR, "");
// String retDirStr = null;
// if(latestMusicDir == null || latestMusicDir.trim().length() == 0){
// retDirStr = rootDir+"1/1/1/";
// }else{
// File someDir = new File(latestMusicDir);
// File[] fileList = someDir.listFiles();
// if(fileList == null || fileList.length<MAX_FILE_NUM_PER_DIR){
// retDirStr = latestMusicDir;
// }else{
// String lastDirStr = latestMusicDir.substring(rootDir.length());
// String[] lastDirs = lastDirStr.split("/",0);
// String someDirStr = rootDir+lastDirs[0]+"/"+lastDirs[1];
// someDir = new File(someDirStr);
// fileList = someDir.listFiles();
// if(fileList == null || fileList.length<MAX_DIR_NUM){
// int thirdDirNum = Integer.parseInt(lastDirs[2]);
// retDirStr =
// rootDir+lastDirs[0]+"/"+lastDirs[1]+"/"+String.valueOf(thirdDirNum+1)+"/";
//
// }else{
//
// someDirStr = rootDir+lastDirs[0]+"/";
// someDir = new File(someDirStr);
// fileList = someDir.listFiles();
// if(fileList == null || fileList.length<MAX_DIR_NUM){
// int secondDirNum = Integer.parseInt(lastDirs[1]);
// retDirStr =
// rootDir+lastDirs[0]+"/"+String.valueOf(secondDirNum+1)+"/1/";
//
// }else{
// someDirStr = rootDir;
// someDir = new File(someDirStr);
// fileList = someDir.listFiles();
// if(fileList == null || fileList.length<MAX_DIR_NUM){
// int firstDirNum = Integer.parseInt(lastDirs[0]);
// retDirStr = rootDir+String.valueOf(firstDirNum+1)+"/1/1/";
//
// }else{
//
// }
// }
// }
// }
// }
//
// Editor editor = appSp.edit();
// editor.putString(CenterPrefConstants.LATEST_MUSIC_DIR, retDirStr);
// editor.commit();
// return retDirStr;
// String retDirStr = null;
// Random r = new Random();
// while(true){
// int num1 = r.nextInt(MAX_FILE_NUM_PER_DIR)+1;
// int num2 = r.nextInt(MAX_FILE_NUM_PER_DIR)+1;
// int num3 = r.nextInt(MAX_FILE_NUM_PER_DIR)+1;
// String subDirStr = rootDirStr+num1+"/"+num2+"/"+num3+"/";
// File subDir = new File(subDirStr);
// if(subDir.exists()){
// File[] childFiles = subDir.listFiles();
// if(childFiles == null || childFiles.length<MAX_FILE_NUM_PER_DIR){
// retDirStr = subDirStr;
// break;
// }
// }else{
// retDirStr = subDirStr;
// break;
// }
// }
//
// if(MyLog.isDyeLevel()){
// MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "retDirStr is:"+retDirStr);
// }
// return retDirStr;
String retDirStr = null;
File rootDir = new File(rootDirStr);
File[] firstChildFiles = rootDir.listFiles();
boolean found = false;
if (firstChildFiles == null || firstChildFiles.length == 0) {
found = true;
retDirStr = rootDirStr + "1/1/1/";
} else {
int firstSubDirNum = 0;
FIRST_LOOP: for (int i = 0; i < firstChildFiles.length; i++) {
File loopFirstChildFile = firstChildFiles[i];
if (loopFirstChildFile.isDirectory()) {
firstSubDirNum++;
File[] loopSecondChildFiles = loopFirstChildFile.listFiles();
if (loopSecondChildFiles == null || loopSecondChildFiles.length == 0) {
found = true;
retDirStr = rootDirStr + loopFirstChildFile.getName() + "/1/1/";
break;
} else {
int secondSubDirNum = 0;
SECOND_LOOP: for (int j = 0; j < loopSecondChildFiles.length; j++) {
File loopSecondChildFile = loopSecondChildFiles[j];
if (loopSecondChildFile.isDirectory()) {
secondSubDirNum++;
File[] thirdChildFiles = loopSecondChildFile.listFiles();
if (thirdChildFiles == null || thirdChildFiles.length == 0) {
found = true;
retDirStr = rootDirStr + loopFirstChildFile.getName() + "/"
+ loopSecondChildFile.getName() + "/1/";
break FIRST_LOOP;
} else {
int thirdSubDirNum = 0;
THIRD_LOOP: for (int k = 0; k < thirdChildFiles.length; k++) {
File loopThirdChildFile = thirdChildFiles[k];
if (loopThirdChildFile.isDirectory()) {
thirdSubDirNum++;
File[] loopForthChildFiles = loopThirdChildFile.listFiles();
if (loopForthChildFiles == null
|| loopForthChildFiles.length < MAX_FILE_NUM_PER_DIR) {
found = true;
retDirStr = rootDirStr + loopFirstChildFile.getName() + "/"
+ loopSecondChildFile.getName() + "/"
+ loopThirdChildFile.getName() + "/";
break FIRST_LOOP;
}
}
}
if (thirdSubDirNum < MAX_DIR_NUM) {
found = true;
retDirStr = rootDirStr + loopFirstChildFile.getName() + "/"
+ loopSecondChildFile.getName() + "/" + (thirdSubDirNum + 1) + "/";
break FIRST_LOOP;
}
}
}
}
if (secondSubDirNum < MAX_DIR_NUM) {
found = true;
retDirStr = rootDirStr + loopFirstChildFile.getName() + "/" + (secondSubDirNum + 1) + "/1/";
break FIRST_LOOP;
}
}
}
}
if (!found) {
if (firstSubDirNum < MAX_DIR_NUM) {
retDirStr = rootDirStr + (firstSubDirNum + 1) + "/1/1/";
} else {
throw new IllegalStateException("file num too many,exceed max save num");
}
}
}
if (MyLog.isDyeLevel()) {
MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "retDirStr is:" + retDirStr);
}
return retDirStr;
}
public static boolean copyFile(File src, File dest, String logTag) {
FileInputStream fis = null;
FileOutputStream fos = null;
if (MyLog.isDyeLevel()) {
MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "begin copy file");
}
if (!dest.exists()) {
File destPFile = dest.getParentFile();
if (destPFile != null) {
destPFile.mkdirs();
}
}
long beginTime = System.currentTimeMillis();
long srcSize = src.length();
boolean retValue = false;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
byte[] buffer = new byte[2048 * 100];
int readByteNum = -1;
while ((readByteNum = fis.read(buffer)) != -1) {
fos.write(buffer, 0, readByteNum);
}
if (MyLog.isDyeLevel()) {
long costTime = System.currentTimeMillis() - beginTime;
MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "srcSize is:" + srcSize + ",costTime is:" + costTime);
}
retValue = true;
} catch (Exception ex) {
if (MyLog.isDyeLevel()) {
MyLog.log(logTag, MyLog.DYE_LOG_LEVEL, "copy file failed", ex);
}
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ioEx) {
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException ioEx) {
}
}
if (!retValue) {
if (dest.exists()) {
dest.delete();
}
}
}
return retValue;
}
public static void deleteDirectory(File dir) {
if (dir == null) {
return;
}
if (MyLog.isDyeLevel()) {
MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "deleteDirectory() is called,begin delete file " + dir);
}
if (dir.isDirectory()) {
File[] childFiles = dir.listFiles();
if (childFiles != null) {
for (int i = 0; i < childFiles.length; i++) {
if (childFiles[i].isFile()) {
childFiles[i].delete();
} else {
deleteDirectory(childFiles[i]);
}
}
}
dir.delete();
} else {
dir.delete();
}
}
public static void findFileWithSpecialSuffixesList(String path, String[] suffixArray, List<File> foundFileList) {
if (MyLog.isDyeLevel()) {
MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "path is:" + path);
}
if (path == null || path.trim().length() == 0) {
return;
}
File f = new File(path);
if (f.isDirectory()) {
File[] childFiles = f.listFiles();
if (childFiles != null && childFiles.length > 0) {
for (int i = 0; i < childFiles.length; i++) {
File loopFile = childFiles[i];
if (loopFile.isDirectory()) {
findFileWithSpecialSuffixesList(loopFile.getAbsolutePath(), suffixArray, foundFileList);
} else {
if (MyLog.isDyeLevel()) {
MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "path is:" + loopFile.getAbsolutePath());
}
String name = loopFile.getName();
int dotIndex = name.lastIndexOf('.');
if (dotIndex >= 0) {
String loopSuffix = name.substring(dotIndex);
if (Arrays.binarySearch(suffixArray, loopSuffix) >= 0) {
foundFileList.add(loopFile);
}
}
}
}
}
} else {
String name = f.getName();
int dotIndex = name.lastIndexOf('.');
if (dotIndex >= 0) {
String loopSuffix = name.substring(dotIndex);
if (Arrays.binarySearch(suffixArray, loopSuffix) >= 0) {
foundFileList.add(f);
}
}
}
}
public static StorageVolume[] getVolumeList() {
try {
StorageManager storageManager = (StorageManager) CenterService.getContext()
.getSystemService(Context.STORAGE_SERVICE);
Method getVolumeListMethod = storageManager.getClass().getDeclaredMethod("getVolumeList", new Class[] {});
StorageVolume[] volumeArray = (StorageVolume[]) getVolumeListMethod.invoke(storageManager, new Object[] {});
return volumeArray;
} catch (Exception ex) {
if (MyLog.isDyeLevel()) {
MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "get volume list fail", ex);
}
return null;
}
}
public static String getSecondStoragePath() {
StorageVolume[] volumeArray = getVolumeList();
if (volumeArray != null && volumeArray.length > 0) {
for (int i = 0; i < volumeArray.length; i++) {
StorageVolume vol = volumeArray[i];
if (MyLog.isDyeLevel()) {
MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "volume path is:" + vol.getPath() + ",isPrimary is:"
+ vol.isPrimary() + ",isRemovable is:" + vol.isRemovable());
}
if (!vol.isPrimary()) {
return vol.getPath();
}
}
}
return "";
}
/**
* 按行读取txt
*
* @param is
* @return
* @throws Exception
*/
public static String readTextFromFile(InputStream is) throws Exception {
// InputStreamReader reader = new InputStreamReader(is);
InputStreamReader reader = new InputStreamReader(is, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuffer buffer = new StringBuffer("");
String str;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
buffer.append("\n");
}
return buffer.toString();
}
public static String getUpgradeAppDir() {
return Environment.getExternalStorageDirectory().getAbsolutePath()+CenterConstants.DISK_ROOT_UPGRADE_CACHE_PATH +"/upgradeapp/";
}
public static String getCenterUpgradeDir() {
return Environment.getExternalStorageDirectory().getAbsolutePath()+CenterConstants.DISK_ROOT_UPGRADE_CACHE_PATH +"/centerapp/";
}
public static boolean copyApkFromAssets(Context context, String fileName, String path) {
boolean copyIsFinish = false;
try {
// is =
// mContext.getResources().getAssets().open("app/MetBaoUpgrade_Signed_1.1.apk");
InputStream is = context.getResources().getAssets().open(fileName);
File file = new File(path);
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
byte[] temp = new byte[1024];
int i = 0;
while ((i = is.read(temp)) > 0) {
fos.write(temp, 0, i);
}
fos.close();
is.close();
copyIsFinish = true;
} catch (IOException e) {
// e.printStackTrace();
copyIsFinish = false;
}
return copyIsFinish;
}
private static final int BUFFER = 8192;
/**
* 判断文件文件是否存在
*
* @param path
* 文件路径
* @return
*/
public static boolean existFile(String path) {
String filePath = path;
File file = new File(filePath);
if (file.exists()) {
return true;
}
return false;
}
/**
* 判断文件是否存在
*
* @param path
* 文件路径
* @return
*/
public static boolean isFile(String path) {
String filePath = path;
File file = new File(filePath);
if (file.exists() && file.isFile()) {
return true;
}
return false;
}
/**
* 判断文件是否存在
*
* @param path
* 文件路径
* @return
*/
public static boolean isFile(File file) {
if (file.exists() && file.isFile()) {
return true;
}
return false;
}
/**
* 判断文件是否是空文件
*
* @param path
* 文件路径
* @return
*/
public static boolean isNullFile(String path) {
String filePath = path;
File file = new File(filePath);
if (file.exists() && file.isFile() && file.length()<=0) {
return true;
}
return false;
}
/**
* 判断文件是否是空文件
*
* @param path
* 文件路径
* @return
*/
public static boolean isNullFile(File file) {
if (file.exists() && file.isFile() && file.length()<=0) {
return true;
}
return false;
}
/**
* 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!)
*
* @param res
* 原字符串
* @param filePath
* 文件路径
* @return 成功标记
*/
public static boolean string2File(String res, String filePath) {
boolean flag = true;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
File distFile = new File(filePath);
if (!distFile.getParentFile().exists())
distFile.getParentFile().mkdirs();
bufferedReader = new BufferedReader(new StringReader(res));
bufferedWriter = new BufferedWriter(new FileWriter(distFile));
char buf[] = new char[1024]; // 字符缓冲区
int len;
while ((len = bufferedReader.read(buf)) != -1) {
bufferedWriter.write(buf, 0, len);
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
//e.printStackTrace();
flag = false;
return flag;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
//e.printStackTrace();
flag = false;
}
}
}
return flag;
}
/**
* 文本文件转换为指定编码的字符串
*
* @param file
* 文本文件
* @param encoding
* 编码类型
* @return 转换后的字符串
* @throws java.io.IOException
*/
public static String file2String(File file, String encoding) {
InputStreamReader reader = null;
StringWriter writer = new StringWriter();
try {
if (encoding == null || "".equals(encoding.trim())) {
reader = new InputStreamReader(new FileInputStream(file));
} else {
reader = new InputStreamReader(new FileInputStream(file), encoding);
}
// 将输入流写入输出流
char[] buffer = new char[1024];
int n = 0;
while (-1 != (n = reader.read(buffer))) {
writer.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 返回转换结果
if (writer != null)
return writer.toString();
else
return null;
}
/**
* 删除目录(文件夹)以及目录下的文件
*
* @param path
* 被删除目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean createDirectory(String path) {
File outFile = new File(path);
if (!outFile.exists())
return outFile.mkdirs();
return true;
}
/**
* 根据路径删除指定的目录或文件,无论存在与否
*
* @param path
* 要删除的目录或文件
* @return 删除成功返回 true,否则返回 false。
*/
public static boolean deleteFolder(String path) {
boolean flag = false;
File file = new File(path);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
return deleteFile(path);
} else { // 为目录时调用删除目录方法
return deleteDirectory(path);
}
}
}
/**
* 删除目录(文件夹)以及目录下的文件
*
* @param path
* 被删除目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String path) {
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!path.endsWith(File.separator)) {
path = path + File.separator;
}
File dirFile = new File(path);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
// 删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
if (files != null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
} // 删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag)
break;
}
}
}
if (!flag)
return false;
// 删除当前目录
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
/**
* 删除单个文件
*
* @param path
* 被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String path) {
boolean flag = false;
File file = new File(path);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
// 读取文件
public static String readTextFile(File file) throws IOException {
String text = null;
InputStream is = null;
try {
is = new FileInputStream(file);
text = readTextInputStream(is);
} finally {
if (is != null) {
is.close();
}
}
return text;
}
// 从流中读取文件
public static String readTextInputStream(InputStream is) throws IOException {
StringBuffer strbuffer = new StringBuffer();
String line;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
strbuffer.append(line).append("\r\n");
}
} finally {
if (reader != null) {
reader.close();
}
}
return strbuffer.toString();
}
// 将文本内容写入文件
public static void writeTextFile(File file, String str) throws IOException {
DataOutputStream out = null;
try {
out = new DataOutputStream(new FileOutputStream(file));
out.write(str.getBytes());
} finally {
if (out != null) {
out.close();
}
}
}
// 复制文件
public static void copyFile(File sourceFile, File targetFile) throws IOException {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
try {
inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] buffer = new byte[BUFFER];
int length;
while ((length = inBuff.read(buffer)) != -1) {
outBuff.write(buffer, 0, length);
}
outBuff.flush();
} finally {
if (inBuff != null) {
inBuff.close();
}
if (outBuff != null) {
outBuff.close();
}
}
}
/**
* 解压缩
*
* @param zipPathFile
* 要解压的文件
* @param sDestPath
* 解压到某文件夹
* @return
*/
public static ArrayList decmpression(String zipPathFile, String sDestPath) {
ArrayList<String> allFileName = new ArrayList<String>();
try {
// 先指定压缩档的位置和档名,建立FileInputStream对象
FileInputStream fins = new FileInputStream(zipPathFile);
// 将fins传入ZipInputStream中
ZipInputStream zins = new ZipInputStream(fins);
ZipEntry ze = null;
byte[] ch = new byte[256];
while ((ze = zins.getNextEntry()) != null) {
File zfile = new File(sDestPath + ze.getName());
File fpath = new File(zfile.getParentFile().getPath());
if (ze.isDirectory()) {
if (!zfile.exists())
zfile.mkdirs();
zins.closeEntry();
} else {
if (!fpath.exists())
fpath.mkdirs();
FileOutputStream fouts = new FileOutputStream(zfile);
int i;
allFileName.add(zfile.getAbsolutePath());
while ((i = zins.read(ch)) != -1)
fouts.write(ch, 0, i);
zins.closeEntry();
fouts.close();
}
}
fins.close();
zins.close();
} catch (Exception e) {
System.err.println("Extract error:" + e.getMessage());
}
return allFileName;
}
/**
* 解压缩
*
* @param zipFile
* 要解压的文件
* @param destPath
* 解压到某文件夹
* @return
*/
public static ArrayList decmpression(File zipFile, String destPath) {
ArrayList<String> allFileName = new ArrayList<String>();
try {
// 先指定压缩档的位置和档名,建立FileInputStream对象
FileInputStream fins = new FileInputStream(zipFile);
// 将fins传入ZipInputStream中
ZipInputStream zins = new ZipInputStream(fins);
ZipEntry ze = null;
byte[] ch = new byte[256];
while ((ze = zins.getNextEntry()) != null) {
File zfile = new File(destPath + ze.getName());
File fpath = new File(zfile.getParentFile().getPath());
if (ze.isDirectory()) {
if (!zfile.exists())
zfile.mkdirs();
zins.closeEntry();
} else {
if (!fpath.exists())
fpath.mkdirs();
FileOutputStream fouts = new FileOutputStream(zfile);
int i;
allFileName.add(zfile.getAbsolutePath());
while ((i = zins.read(ch)) != -1)
fouts.write(ch, 0, i);
zins.closeEntry();
fouts.close();
}
}
fins.close();
zins.close();
} catch (Exception e) {
System.err.println("Extract error:" + e.getMessage());
}
return allFileName;
}
/*
* public long getFileSizes(File f) throws Exception{//取得文件大小 long s=0; if
* (f.exists()) { FileInputStream fis = null; fis = new FileInputStream(f);
* s= fis.available(); } else { f.createNewFile();
* System.out.println("文件不存在"); } return s; }
*/
// 递归取得文件夹(包括子目录)中所有文件的大小
public static long getFileSize(File f) throws Exception// 取得文件夹大小
{
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSize(flist[i]);
} else {
size = size + flist[i].length();
}
}
return size;
}
public static String FormetFileSize(long fileS) {// 转换文件大小
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
public static long getlist(File f) {// 递归求取目录文件个数
long size = 0;
File flist[] = f.listFiles();
size = flist.length;
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getlist(flist[i]);
size--;
}
}
return size;
}
public static long getDir(File f) {// 递归求取目录中文件(包括目录)的个数
long size = 0;
File flist[] = f.listFiles();
size = flist.length;
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getDir(flist[i]);
}
}
return size;
}
public static long getRootDirCount(File f) {// 递归求取目录中目录(不包括子目录)的个数
long size = 0;
File flist[] = f.listFiles();
size = flist.length;
if (f == null || !f.isDirectory())
return 0;
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory())
size = size + 1;
}
return size;
}
public static List<String> getRootDirs(File f) {// 递归求取目录中目录(不包括子目录)的目录名称信息
List<String> dirs = new ArrayList<String>();
long size = 0;
File flist[] = f.listFiles();
size = flist.length;
if (f == null || !f.isDirectory())
dirs = null;
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory())
dirs.add(flist[i].getName());
}
return dirs.isEmpty() ? null : dirs;
}
public static void main(String args[]) {
FileUtil g = new FileUtil();
long startTime = System.currentTimeMillis();
try {
long l = 0;
String path = "D:\\tomcat7\\webapps\\cwbwebhome";
File ff = new File(path);
if (ff.isDirectory()) { // 如果路径是文件夹的时候
System.out.println("文件个数 " + g.getlist(ff));
System.out.println("文件和目录总个数 " + g.getDir(ff));
System.out.println("目录");
l = g.getFileSize(ff);
System.out.println(path + "目录的大小为:" + g.FormetFileSize(l));
} else {
System.out.println(" 文件个数 1");
System.out.println("文件");
l = g.getFileSize(ff);
System.out.println(path + "文件的大小为:" + g.FormetFileSize(l));
}
} catch (Exception e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("总共花费时间为:" + (endTime - startTime) + "毫秒...");
}
}
FileUtil工具类
最新推荐文章于 2025-07-02 23:18:51 发布
本文深入探讨了Java中文件操作的多种方法,包括文件的读写、复制、删除及目录的创建与遍历等核心功能。文章详细介绍了如何使用Java进行文件的查找、文件属性的获取、文件的压缩与解压缩,以及如何处理大文件和目录结构。此外,还提供了文件大小和数量的统计方法,以及文件系统的监控和优化技巧。
1042

被折叠的 条评论
为什么被折叠?



