import java.io.File;
import java.io.FileOutputStream;
import android.os.Environment;
import com.iszcc.x5audio.activity.MyApplication;
/**
* 文件工具类
*
* @author king
*
*/
public class FileUtils {
private static FileUtils instance;
public FileUtils() {
}
public static FileUtils getInstance() {
if (instance == null) {
synchronized (FileUtils.class) {
if (instance == null) {
instance = new FileUtils();
}
}
}
return instance;
}
/**
* 写文件
*
* @param fileName
* @param configByte
* @return
*/
public boolean writeFile(String fileName, String configByte) {
boolean flag = false;
String filePath = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
filePath = Environment.getExternalStorageDirectory().toString() + File.separator + Constants.FILE_PATH + File.separator + fileName + ".txt";
LogUtil.e("Tag", "filepath" + filePath);
} else {
flag = false;
Toast.makeText(MyApplication.getInstace().getApplicationContext(), "文件系统有问题", Toast.LENGTH_SHORT).show();
return flag;
}
FileOutputStream outputStream = null;
try {
File file = new File(filePath);
if (!file.exists()) {
LogUtil.e("Tag", "file.exists()" + filePath);
File dir = new File(file.getParent());
dir.mkdirs();
file.createNewFile();
}
outputStream = new FileOutputStream(file);
outputStream.write(configByte.getBytes());
flag = true;
} catch (Exception e) {
LogUtil.e("文件写入异常");
e.printStackTrace();
flag = false;
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 读文件
*
* @param fileName
* @return
*/
public String readFile(String fileName) {
if (fileName == null) {
return null;
}
String fileString = null;
String filePath = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
filePath = Environment.getExternalStorageDirectory().toString() + File.separator + Constants.FILE_PATH + File.separator + fileName + ".txt";
LogUtil.e("Tag", "filepath" + filePath);
} else {
Toast.makeText(MyApplication.getInstace().getApplicationContext(), "文件系统有问题", Toast.LENGTH_SHORT).show();
}
StringBuilder stringBuilder = new StringBuilder();
File file = new File(filePath);
if (file.isDirectory()) {
LogUtil.e("Tag", filePath + " is directory");
return null;
}
if (!file.exists()) {
Toast.makeText(MyApplication.getInstace().getApplicationContext(), "文件不存在", Toast.LENGTH_SHORT).show();
} else {
try {
InputStream is = new FileInputStream(file);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
stringBuilder.append(line);
LogUtil.e("Tag", line);
}
fileString = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
LogUtil.e("Tag", filePath + " doesn't found!");
} catch (IOException e) {
LogUtil.e("Tag", filePath + " read exception, " + e.getMessage());
}
}
return fileString;
}
/**
* 获取目录下所有文件(按时间排序)
*
* @param path
* @return
*/
public List<File> listFileSortByModifyTime(String path) {
List<File> fileList = getFiles(path, new ArrayList<File>());
if (fileList != null && fileList.size() > 0) {
Collections.sort(fileList, new Comparator<File>() {
public int compare(File file, File newFile) {
if (file.lastModified() < newFile.lastModified()) {
return -1;
} else if (file.lastModified() == newFile.lastModified()) {
return 0;
} else {
return 1;
}
}
});
}
return fileList;
}
/**
* 获取目录下的所有文件
*
* @param realPath 文件夹目录
* @param files
* @return
*/
public List<File> getFiles(String realPath, List<File> files) {
File realFile = new File(realPath);
if (!realFile.exists()) {
return files;
}
if (realFile.isDirectory()) {
File[] subFils = realFile.listFiles();
for (File file : subFils) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
}
}
return files;
}
/**
* 获取SD卡剩余容量大小(单位Byte)
*
* @return
*/
public static long getSDFreeSize() {
//取得SD卡文件路径
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
//获取单个数据块的大小(Byte)
long blockSize = sf.getBlockSize();
//空闲的数据块的数量
long freeBlocks = sf.getAvailableBlocks();
//返回SD卡空闲大小
return freeBlocks * blockSize;
//单位Byte
// return (freeBlocks * blockSize)/1024;
// 单位KB
// return (freeBlocks * blockSize) / 1024 / 1024;
// 单位MB }
}
/**
* 重命名 * * @param filePath * @return
*/
public boolean rename(String fileName, String newFileName) {
String filePath = Environment.getExternalStorageDirectory().toString() + File.separator + Constants.FILE_PATH + File.separator + fileName + ".txt";
String newFilePath = Environment.getExternalStorageDirectory().toString() + File.separator + Constants.FILE_PATH + File.separator + newFileName + ".txt";
if (LogUtil.DEBUG) {
LogUtil.e("filePath " + filePath);
LogUtil.e("newFilePath " + newFilePath);
}
if (!TextUtils.isEmpty(filePath)) {
final File file = new File(filePath);
final File newFile = new File(newFilePath);
if (file.exists()) {
return file.renameTo(newFile);
}
}
return false;
}
/**
* 删除文件 * * @param filePath * @return
*/
public boolean deleteFile(String fileName) {
String filePath = Environment.getExternalStorageDirectory().toString() + File.separator + Constants.FILE_PATH + File.separator + fileName + ".txt";
if (LogUtil.DEBUG) {
LogUtil.e("deleteFile path " + filePath);
}
if (!TextUtils.isEmpty(filePath)) {
final File file = new File(filePath);
if (LogUtil.DEBUG) {
LogUtil.e("deleteFile path exists " + file.exists());
}
if (file.exists()) {
return file.delete();
}
}
return false;
}
// 根缓存目录
private static String cacheRootPath = "";
/**
* sd卡是否可用
*
* @return
*/
public static boolean isSdCardAvailable() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* 创建根缓存目录
*
* @return
*/
public static String createRootPath() {
if (isSdCardAvailable()) {
// /sdcard/Android/data/<application package>/cache
cacheRootPath = MyApplication.getInstace().getApplicationContext().getExternalCacheDir()
.getPath();
} else {
// /data/data/<application package>/cache
cacheRootPath = MyApplication.getInstace().getApplicationContext().getCacheDir().getPath();
}
return cacheRootPath;
}
/**
* 创建文件夹
*
* @param dirPath
* @return 创建失败返回""
*/
private static String createDir(String dirPath) {
try {
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
return dir.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
return dirPath;
}
/**
* 获取图片缓存目录
*
* @return 创建失败,返回""
*/
public static String getImageCachePath() {
String path = createDir(createRootPath() + File.separator + "img"
+ File.separator);
return path;
}
/**
* 获取图片裁剪缓存目录
*
* @return 创建失败,返回""
*/
public static String getImageCropCachePath() {
String path = createDir(createRootPath() + File.separator + "imgCrop"
+ File.separator);
return path;
}
/**
* 删除文件或者文件夹
*
* @param file
*/
public static void deleteFileOrDirectory(File file) {
try {
if (file.isFile()) {
file.delete();
return;
}
if (file.isDirectory()) {
File[] childFiles = file.listFiles();
// 删除空文件夹
if (childFiles == null || childFiles.length == 0) {
file.delete();
return;
}
// 递归删除文件夹下的子文件
for (int i = 0; i < childFiles.length; i++) {
deleteFileOrDirectory(childFiles[i]);
}
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将内容写入文件
*
* @param filePath
* eg:/mnt/sdcard/demo.txt
* @param content
* 内容
*/
public static void writeFileSdcard(String filePath, String content,
boolean isAppend) {
try {
FileOutputStream fout = new FileOutputStream(filePath, isAppend);
byte[] bytes = content.getBytes();
fout.write(bytes);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}