1、创建文件或文件夹
/**
* 创建文件或文件夹
*/
public static boolean createFileDir(File dirFile) {
if (dirFile == null) return true;
if (dirFile.exists()) return true;
File parentFile = dirFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
//父文件夹不存在,则先创建父文件夹,再创建自身文件夹
return createFileDir(parentFile) && createFileDir(dirFile);
} else {
boolean mkdirs = dirFile.mkdirs();
boolean isSuccess = mkdirs || dirFile.exists();
return isSuccess;
}
}
2、删除文件或文件夹
/**
* 删除文件或文件夹
*/
public static void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
}
}
// 删除文件夹
file.delete();
}
}
3、获取文件夹数量
/**
* 获取文件数量
*/
public static int getFileNum(File file) {
int fileNum = 0;
if (file.exists() && file.isDirectory()) {
File files[] = file.listFiles();
if (files != null) {
fileNum = files.length;
}
}
return fileNum;
}
4、压缩文件或文件夹
/**
* 压缩文件和文件夹
* @param srcFileString 要压缩的文件或文件夹
* @param zipFileString 压缩完成的Zip路径
* @param notFile 忽略压缩文件
* @throws Exception
*/
public static void ZipFolder(String srcFileString, String zipFileString) {
try {
ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));
File file = new File(srcFileString);
ZipFiles(file.getParent() + File.separator, file.getName(), outZip);
outZip.finish();
outZip.close();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 压缩文件
* @param folderString
* @param fileString
* @param zipOutputSteam
* @throws Exception
*/
private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {
if (zipOutputSteam == null)
return;
File file = new File(folderString + fileString);
if (file.isFile()) {
ZipEntry zipEntry = new ZipEntry(fileString);
FileInputStream inputStream = new FileInputStream(file);
zipOutputSteam.putNextEntry(zipEntry);
int len;
byte[] buffer = new byte[4096];
while ((len = inputStream.read(buffer)) != -1) {
zipOutputSteam.write(buffer, 0, len);
}
zipOutputSteam.closeEntry();
} else {
String fileList[] = file.list();
if (fileList.length <= 0) {
ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
zipOutputSteam.putNextEntry(zipEntry);
zipOutputSteam.closeEntry();
}
//子文件和递归
for (int i = 0; i < fileList.length; i++) {
ZipFiles(folderString + fileString + "/", fileList[i], zipOutputSteam);
}
}
}
5、文件列表排序
public static File[] orderByName(File file) {
File[] files = file.listFiles();
Collections.sort(Arrays.asList(files));
return files;
}
6、文件内容监听
/**
*监听文件或文件夹变化
*/
private FileObserver fileObserver = new FileObserver("监听路径") {
@Override
public void onEvent(int event, String path) {//path 触发事件的文件相对监听文件的路径
if (event == FileObserver.CREATE) {
// 监控的文件夹下创建了子文件或文件夹
} else if(event == FileObserver.ACCESS) {
// 文件被读取
} else if(event == FileObserver.ATTRIB) {
// 权限 所有者 时间戳被修改
} else if(event == FileObserver.CLOSE_NOWRITE) {
// 打开并关闭了文件夹(未修改)
} else if(event == FileObserver.CLOSE_WRITE) {
// 打开并关闭了文件夹(有修改)
} else if(event == FileObserver.DELETE) {
// 监控的文件夹下删除了子文件或文件夹
} else if(event == FileObserver.DELETE_SELF) {
// 被监控的文件或文件夹被删除,监控停止
} else if(event == FileObserver.MODIFY) {
// 文件被修改
} else if(event == FileObserver.MOVED_FROM) {
// 被监控文件夹有子文件或文件夹移走
} else if(event == FileObserver.MOVED_TO) {
// 被监控文件夹有子文件或文件夹被移入
} else if(event == FileObserver.MOVE_SELF) {
// 被监控文件或文件夹被移动
} else if(event == FileObserver.OPEN) {
// 文件或文件夹被打开
} else if(event == FileObserver.ALL_EVENTS) {
// 以上所有事件
}
}
};
//开始监听
fileObserver.startWatching();
//结束监听
fileObserver.stopWatching();
7、文件重命名
/**
* 文件重命名
* @param filePath 文件路径
* @param reName 文件新名
*/
public void chageFileName(String filePath, String reName){
File file = new File(filePath);
String path = filePath.substring(0, filePath.lastIndexOf("/") + 1) + reName;
File newFile = new File(path);
file.renameTo(newFile);
}
8、复制文件和文件夹
/**
* 复制单个文件
* @param oldPath String 原文件路径
* @param newPath String 复制后路径
* @return boolean
*/
public static void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
} else {
System.out.println("文件不存在");
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
/**
* 复制整个文件夹内容
* @param oldPath String 原文件路径
* @param newPath String 复制后路径
* @return boolean
*/
public void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}
else{
temp=new File(oldPath+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
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(temp.isDirectory()){//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
9、文件转Byte数组
/**
* 文件转换byte[]
* @param path 文件路径
* @return
*/
public static byte[] File2Bytes(String path) {
File file = new File(path);
int byte_size = 1024;
byte[] b = new byte[byte_size];
try {
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
byte_size);
for (int length; (length = fileInputStream.read(b)) != -1;) {
outputStream.write(b, 0, length);
}
fileInputStream.close();
outputStream.close();
return outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
10、文件解压
public class UnzipFileUtils {
public static final String TAG = "UnzipFileUtils";
private UnzipManagerCallBack mUnzipCallback;
private static UnzipFileUtils instance;
private File zipFile;
// 已解压文件大小
double temp = 0;
long l;
private int mProgress = 0;
private boolean unzipError = false;
private int unzipResult = -1;
private UnzipFileUtils() {
}
public static synchronized UnzipFileUtils getInstance() {
if (null == instance) {
instance = new UnzipFileUtils();
}
return instance;
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void unzipFile(String zipPath, String descDir, FotaManagerImpl.FotaManagerCallBack unzipCallback) {
temp = 0;
mProgress = 0;
mUnzipCallback = unzipCallback;
mUnzipCallback.onStart();
zipFile = new File(zipPath);
l = getZipTrueSize(zipPath);
try {
if (!zipFile.exists()) {
mUnzipCallback.onError(Constant.ERROR_UNZIP);
Log.d(TAG, "unzipFile: the compressed package does not exist.");
}
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
InputStream input = new FileInputStream(zipPath);
unzipWithStream(input, descDir);
} catch (Exception e) {
e.printStackTrace();
}
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void unzipWithStream(InputStream inputStream, String descDir) {
if (!descDir.endsWith(File.separator)) {
descDir = descDir + File.separator;
}
try {
ZipInputStream zipInputStream = new ZipInputStream(inputStream, Charset.forName("GBK"));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String zipEntryNameStr = zipEntry.getName();
String zipEntryName = zipEntry.getName();
if (zipEntryNameStr.contains("/")) {
String str1 = zipEntryNameStr.substring(0, zipEntryNameStr.indexOf("/"));
zipEntryName = zipEntryNameStr.substring(str1.length() + 1);
}
String outPath = (descDir + zipEntryName).replace("\\\\", "/");
File outFile = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!outFile.exists()) {
outFile.mkdirs();
}
if (new File(outPath).isDirectory()) {
continue;
}
writeFile(outPath, zipInputStream);
zipInputStream.closeEntry();
}
inputStream.close();
mUnzipCallback.onComplete();
Log.d(TAG, "===== unzip onComplete() =====");
} catch (IOException e) {
e.printStackTrace();
mUnzipCallback.onError(Constant.ERROR_UNZIP);
}
}
private void writeFile(String filePath, ZipInputStream zipInputStream) {
try {
OutputStream outputStream = new FileOutputStream(filePath);
byte[] bytes = new byte[4096];
int len;
while ((len = zipInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
temp += len;
setProgress();
}
} catch (IOException e) {
e.printStackTrace();
mUnzipCallback.onError(Constant.ERROR_UNZIP);
}
}
private void setProgress() {
//计算百分比
double t = temp / l;
int progress = (int) (t * 100);
if (progress != mProgress) {
mProgress = progress;
mUnzipCallback.onProgress("解压升级包", progress);
}
}
public long getZipTrueSize(String filePath) {
long size = 0;
ZipFile f;
try {
f = new ZipFile(filePath);
Enumeration<? extends ZipEntry> en = f.entries();
while (en.hasMoreElements()) {
size += en.nextElement().getSize();
}
} catch (IOException e) {
e.printStackTrace();
}
return size;
}
}