package com.cc.moxingvoice.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import com.cc.moxingvoice.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
/**
* 創建日期:2018/2/28 on 14:33
* 描述:
* 作者:郭士超
* QQ:1169380200
*/
public class FilesUtil {
// 獲取當前目錄下所有的文件夾
public static Vector<String> getFolderName(String fileAbsolutePath) {
Vector<String> vecFile = new Vector<String>();
File file = new File(fileAbsolutePath);
File[] subFile = file.listFiles();
if (subFile == null) {
return vecFile;
}
for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
// 判斷是否爲文件夾
if (subFile[iFileLength].isDirectory()) {
String filename = subFile[iFileLength].getName();
vecFile.add(filename);
}
}
return vecFile;
}
// 獲取當前目錄下所有的mp3文件
public static Vector<String> getVoiceFileName(String fileAbsolutePath) {
Vector<String> vecFile = new Vector<String>();
File file = new File(fileAbsolutePath);
File[] subFile = file.listFiles();
for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
// 判斷是否爲文件夾
if (!subFile[iFileLength].isDirectory()) {
String filename = subFile[iFileLength].getName();
// 判斷是否爲MP3結尾
if (filename.trim().toLowerCase().endsWith(".mp3")
|| filename.trim().toLowerCase().endsWith(".wma")
|| filename.trim().toLowerCase().endsWith(".arm")
|| filename.trim().toLowerCase().endsWith(".m4a")
|| filename.trim().toLowerCase().endsWith(".wav")
// QQ的,需要特殊處理
|| filename.trim().toLowerCase().endsWith(".slk")
|| filename.trim().toLowerCase().endsWith(".amr")
// 我自己的
|| filename.trim().toLowerCase().endsWith(".mvod")) {
vecFile.add(filename);
}
}
}
return vecFile;
}
// 遍歷所有的mp3文件
public static Vector<String> getAllVoiceFileName(String strPath) {
Vector<String> voiceList = new Vector<String>();
String filename;//文件名
String suf;//文件後綴
File dir = new File(strPath);//文件夾dir
File[] files = dir.listFiles();//文件夾下的所有文件或文件夾
if (files == null) {
return voiceList;
}
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
voiceList.addAll(getAllVoiceFileName(files[i].getAbsolutePath())); // 遞歸文件夾!!!
} else {
filename = files[i].getName();
int j = filename.lastIndexOf(".");
suf = filename.substring(j + 1);//得到文件後綴
// 判斷是否爲MP3結尾
if (suf.equalsIgnoreCase("slk")
|| suf.equalsIgnoreCase("amr")) {
String strFileName = files[i].getAbsolutePath().toLowerCase();
voiceList.add(files[i].getAbsolutePath()); // 對於文件才把它的路徑加到filelist中
}
}
}
return voiceList;
}
// 獲取文件創建時間
public static long getFileTime(String filePath) {
File f = new File(filePath);
if (f.exists()) {
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
// 文件文件創建時間
// String time = new SimpleDateFormat("yyyy-MM-dd")
// .format(new Date(f.lastModified()));
return f.lastModified();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
return 0;
}
// 通過路徑獲取文件名,帶後綴
public static String getFileNameHandExtension(String pathHandName) {
if (!isFileExists(pathHandName)) {
return "未知路徑";
}
int start = pathHandName.lastIndexOf("/");
// int end = pathHandName.lastIndexOf(".");
int end = pathHandName.length();
if (start != -1 && end != -1) {
return pathHandName.substring(start + 1, end);
} else {
return "未知文件";
}
}
// android獲取文件及後綴名 不帶.
public static String[] getFileName(String fileName) {
int dot = fileName.lastIndexOf(".");
String str1 = fileName.substring(0, dot);
String str2 = fileName.substring(dot + 1, fileName.length());
String[] name = {str1, str2};
return name;
}
/**
* @param filePath 原始文件路徑
* @param newName 新名稱(有後綴)
* @param admitCopyName 當命名衝突時,是否允許生成副本名(如果是多選重命名的話,是需要允許的;單個文件重命名則設置爲不允許)
* @return 是否修改成功
* @Description 對文件進行重新命名
*/
public static boolean fileRename(String filePath, String newName, boolean admitCopyName) {
//1.判斷參數閾值
if (!isFileExists(filePath) || newName == null || newName.isEmpty()) {
return false;
}
//2.得到原文件全路徑
String oldPath = filePath;
//3-1.得到文件所在路徑
String rootPath = getPathFromFilepath(oldPath); //得到文件所在路徑(即全路徑去掉完整文件名)
//3-2.得到新全路徑
String newPath = makePath(rootPath, newName); //根據根路徑和文件名形成新的完整路徑
//4.比較是否變更了名稱
if (oldPath.endsWith(newPath)) { //和原來名稱一樣,不需要改變
return true;
}
//5.根據新路徑得到File類型數據
File newFile = new File(newPath);
//6.判斷是否已經存在同樣名稱的文件(即出現重名)
if (isFileExists(newPath) && !admitCopyName) { //出現重命名且不允許生成副本名
return false; //重命名失敗
}
//7.循環判斷直到生成可用的副本名
while (newFile.exists()) {
//重命名重名定義規範--Util.getCopyNameFromOriginal(String)-自定義方法:根據自定義規則生成原名稱副本
newPath = getCopyNameFromOriginal(newPath);
newFile = new File(newPath);
}
//8.得到原文件File類型數據
File file = new File(oldPath);
//9.調用固有方法去重命名
boolean ret = file.renameTo(newFile);
/*if (ret) {
//FIXME:這裏通過更改形參來改變實參,是不好的寫法,不建議這樣寫!
fileInfo.setFileName(getNameFromFilepath(newPath)); //更新文件名
fileInfo.setmFilePath(newPath); //更新新路徑
}*/
return ret;
}
/**
* @param originalName 原本的名字,XXX.xx 或者完整路徑 xx/xx/XXX.xx , 也可以沒有後綴.xx
* @return 副本名稱
* @Description 得到文件副本名稱,可供粘貼及多選重命名方法使用
* 命名規則爲:普通文件後加“ 1”,若文件末尾已有“ 數字”,則數字遞增。
* 比如,有個文件叫“我.jpg”,使用本方法後得到了“我 1.jpg”,再次使用本方法後得到“我 2.jpg”
*/
public static String getCopyNameFromOriginal(final String originalName) {
//1.判斷閾值
if (originalName == null || originalName.isEmpty()) {
return null;
}
String copyName = null;
//2.得到文件名和後綴名
String[] nameAndExt = getFileName(getFileNameHandExtension(originalName));
if (nameAndExt == null) {
return null;
}
String fileName = nameAndExt[0];
String fileExt = nameAndExt[1];
//3.判斷文件名是否包含我們定義副本規範的標記字符(空格) 原來是空格,我改爲_下劃線
// String mark = " "; // 原來是空格,我改爲_下劃線
String mark = "_"; // 原來是空格,我改爲_下劃線
if (fileName.contains(mark)) { //如果文件名包涵空格,進行判斷是否已經爲副本名稱
//4-1.得到end
String[] array = fileName.split(mark);
String end = array[array.length - 1]; //得到標記字符後面的值
//4-2.確保end得到的是最後面的值(防止出現類似路徑中的目錄也有標記字符的情況,如:"mnt/sda/wo de/zhao pian/我的 照片 1.png")
while (end.contains(mark)) {
array = fileName.split(mark);
end = array[array.length - 1];
}
//5.判斷標記字符後的字符串是否複合規範(是否是數字)
boolean isDigit = end.matches("[0-9]+"); //用正則表達式判斷是否是正整數
if (isDigit) {
try {
int index = Integer.parseInt(end) + 1; //遞增副本記數
int position = fileName.lastIndexOf(mark); //得到最後的空格的位置,用於截取前面的字符串
if (position != -1) {
//6-1.構造新的副本名(數字遞增)
copyName = fileName.substring(0, position + 1) + String.valueOf(index);
}
} catch (Exception e) { //轉化成整形錯誤
e.printStackTrace();
return null;
}
} else { //如果空格後不是純數字,即不爲我們定義副本的規範
//6-2.構造新的副本名(數字初始爲1)
copyName = fileName + mark + "1";
}
} else { //如果沒有,則變爲副本名稱格式
//6-3.構造新的副本名(數字初始爲1)
copyName = fileName + mark + "1";
}
//6.返回副本名+後綴名
String newName = getPathFromFilepath(originalName) + "/" + copyName + "." + fileExt;
return newName;
}
/**
* @param filepath 文件全路徑名稱,like mnt/sda/XX.xx
* @return 根路徑,like mnt/sda
* @Description 得到文件所在路徑(即全路徑去掉完整文件名)
*/
public static String getPathFromFilepath(final String filepath) {
int pos = filepath.lastIndexOf('/');
if (pos != -1) {
return filepath.substring(0, pos);
}
return "";
}
/**
* @param path1 路徑一
* @param path2 路徑二
* @return 新路徑
* @Description 重新整合路徑,將路徑一和路徑二通過'/'連接起來得到新路徑
*/
public static String makePath(final String path1, final String path2) {
// 用"/"或File.separator , 原來用的File.separator,可能一樣
if (path1.endsWith("/")) {
return path1 + path2;
}
return path1 + "/" + path2;
}
// 看文件是否存在
public static boolean isFileExists(String path) {
try {
File f = new File(path);
if (!f.exists()) {
return false;
}
} catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}
// 創建文件夾
public static void mkdirPath(String path) {
//獲取內部存儲狀態
String state = Environment.getExternalStorageState();
//如果狀態不是mounted,無法讀寫
if (!state.equals(Environment.MEDIA_MOUNTED)) {
return;
}
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
}
// 修改文件及文件夾名
public static void filesRename(String oldPath, String newPath) {
// new File("f:/a/a.xlsx").renameTo(new File("f:/a/b.xlsx"));
//將原文件夾更改爲A,其中路徑是必要的。注意
new File(oldPath).renameTo(new File(newPath));
}
// 保存圖片到本地
public static void savePic(String path, String fileName, Bitmap bitmap) {
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(path, fileName);
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 保存分享圖片到本地+\
*/
public static void saveSharePic(Context context, String appPath, String fileName) {
//獲取內部存儲狀態
String state = Environment.getExternalStorageState();
//如果狀態不是mounted,無法讀寫
if (!state.equals(Environment.MEDIA_MOUNTED)) {
return;
}
try {
File dir = new File(appPath);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(appPath, fileName);
FileOutputStream out = new FileOutputStream(file);
// 在這裏改分享的圖片哦
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.liyunlong);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 刪除文件,可以是文件或文件夾
*
* @param fileName 要刪除的文件名
* @return 刪除成功返回true,否則返回false
*/
public static boolean delete(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
// System.out.println("刪除文件失敗:" + fileName + "不存在!");
return false;
} else {
if (file.isFile())
return deleteFile(fileName);
else
return deleteDirectory(fileName);
}
}
/**
* 刪除單個文件
*
* @param fileName 要刪除的文件的文件名
* @return 單個文件刪除成功返回true,否則返回false
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路徑所對應的文件存在,並且是一個文件,則直接刪除
if (file.exists() && file.isFile()) {
if (file.delete()) {
// System.out.println("刪除單個文件" + fileName + "成功!");
return true;
} else {
// System.out.println("刪除單個文件" + fileName + "失敗!");
return false;
}
} else {
// System.out.println("刪除單個文件失敗:" + fileName + "不存在!");
return false;
}
}
/**
* 刪除目錄及目錄下的文件
*
* @param dir 要刪除的目錄的文件路徑
* @return 目錄刪除成功返回true,否則返回false
*/
public static boolean deleteDirectory(String dir) {
// 如果dir不以文件分隔符結尾,自動添加文件分隔符
if (!dir.endsWith(File.separator))
dir = dir + File.separator;
File dirFile = new File(dir);
// 如果dir對應的文件不存在,或者不是一個目錄,則退出
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
// System.out.println("刪除目錄失敗:" + dir + "不存在!");
return false;
}
boolean flag = true;
// 刪除文件夾中的所有文件包括子目錄
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 刪除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
}
// 刪除子目錄
else if (files[i].isDirectory()) {
flag = deleteDirectory(files[i]
.getAbsolutePath());
if (!flag)
break;
}
}
if (!flag) {
// System.out.println("刪除目錄失敗!");
return false;
}
// 刪除當前目錄
if (dirFile.delete()) {
// System.out.println("刪除目錄" + dir + "成功!");
return true;
} else {
return false;
}
}
/**
* 複製單個文件
*
* @param oldPath String 原文件路徑 如:c:/fqf.txt
* @param newPath String 複製後路徑 如:f:/fqf.txt
* @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();
}
} catch (Exception e) {
// System.out.println("複製單個文件操作出錯");
e.printStackTrace();
}
}
/**
* 複製整個文件夾內容
*
* @param oldPath String 原文件路徑 如:c:/fqf
* @param newPath String 複製後路徑 如:f:/fqf/ff
* @return boolean
*/
public static 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();
}
}
}