File 文件工具类
import android.content.Context;
import android.os.Environment;
import com.example.myresumemvvm.MyApplication;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* @author 写文件的工具类
*/
public class FileUtil {
public static final String ROOT_DIR = "Android/data/" + CommonUtil.getPackageName();
public static final String DOWNLOAD_DIR = "download";
public static final String CACHE_DIR = "DOWNLOAD_INFO_HASHMAP";
public static final String ICON_DIR = "icon";
private static Context getContext(){
return MyApplication.context;
}
/**
* 获取下载目录
*/
public static String getDownloadDir() {
return getDir(DOWNLOAD_DIR);
}
/**
* 获取缓存目录
*/
public static String getCacheDir() {
return getDir(CACHE_DIR);
}
/**
* 获取icon目录
*/
public static String getIconDir() {
return getDir(ICON_DIR);
}
/**
* 判断SD卡是否挂载
*/
public static boolean isSDCardAvailable() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return true;
} else {
return false;
}
}
/**
* 创建文件夹
*/
public static boolean createDirs(String dirPath) {
File file = new File(dirPath);
if (!file.exists() || !file.isDirectory()) {
return file.mkdirs();
}
return true;
}
/**
* 复制文件,可以选择是否删除源文件
*/
public static boolean copyFile(String srcPath, String destPath, boolean deleteSrc) {
File srcFile = new File(srcPath);
File destFile = new File(destPath);
return copyFile(srcFile, destFile, deleteSrc);
}
/**
* 复制文件,可以选择是否删除源文件
*/
public static boolean copyFile(File srcFile, File destFile, boolean deleteSrc) {
if (!srcFile.exists() || !srcFile.isFile()) {
return false;
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int i = -1;
while ((i = in.read(buffer)) > 0) {
out.write(buffer, 0, i);
out.flush();
}
if (deleteSrc) {
srcFile.delete();
}
} catch (Exception e) {
LogUtil.e(e);
return false;
} finally {
IOUtils.close(out);
IOUtils.close(in);
}
return true;
}
/**
* 获取应用目录,当SD卡存在时,获取SD卡上的目录,当SD卡不存在时,获取应用的cache目录
*/
public static String getDir(String name) {
StringBuilder sb = new StringBuilder();
if (isSDCardAvailable()) {
sb.append(getExternalStoragePath());
} else {
sb.append(getCachePath());
}
sb.append(name);
sb.append(File.separator);
String path = sb.toString();
if (createDirs(path)) {
return path;
} else {
return null;
}
}
/**
* 获取SD下的应用目录
*/
public static String getExternalStoragePath() {
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());
sb.append(File.separator);
sb.append(ROOT_DIR);
sb.append(File.separator);
return sb.toString();
}
/**
* 获取应用的cache目录
*/
public static String getCachePath() {
File f = getContext().getCacheDir();
if (null == f) {
return null;
} else {
return f.getAbsolutePath() + "/";
}
}
/**
* 获取下载后的apk文件
*
* @param dir(所在文件夹)
* @param packageName(apk包名)
* @return
*/
public static File getApk(String dir, String packageName) {
StringBuffer pathBuffer = new StringBuffer(getDir(dir));
pathBuffer.append(File.separator).append(packageName).append(".apk");
return new File(pathBuffer.toString());
}
/**
* 获取下载后的apk
*
* @param packageName
* @return
*/
public static File getApk(String packageName) {
return getApk("apk", packageName);
}
/**
* 依据包名删除apk文件
* @param packageName
*/
public static void deleteApk(String packageName) {
File apk = getApk(packageName);
if (apk != null && apk.exists()) {
apk.delete();
}
}
/**
* 判断文件是否可写
*/
public static boolean isWriteable(String path) {
try {
if (StringUtil.isEmpty(path)) {
return false;
}
File f = new File(path);
return f.exists() && f.canWrite();
} catch (Exception e) {
LogUtil.e(e);
return false;
}
}
/**
* 修改文件的权限,例如"777"等
*/
public static void chmod(String path, String mode) {
try {
String command = "chmod " + mode + " " + path;
Runtime runtime = Runtime.getRuntime();
runtime.exec(command);
} catch (Exception e) {
LogUtil.e(e);
}
}
/**
* 把数据写入文件
*
* @param is 数据流
* @param path 文件路径
* @param recreate 如果文件存在,是否需要删除重建
* @return 是否写入成功
*/
public static boolean writeFile(InputStream is, String path, boolean recreate) {
boolean res = false;
File f = new File(path);
FileOutputStream fos = null;
try {
if (recreate && f.exists()) {
f.delete();
}
if (!f.exists() && null != is) {
File parentFile = new File(f.getParent());
parentFile.mkdirs();
int count = -1;
byte[] buffer = new byte[1024];
fos = new FileOutputStream(f);
while ((count = is.read(buffer)) != -1) {
fos.write(buffer, 0, count);
}
res = true;
}
} catch (Exception e) {
LogUtil.e(e);
} finally {
IOUtils.close(fos);
IOUtils.close(is);
}
return res;
}
/**
* 把字符串数据写入文件
*
* @param content 需要写入的字符串
* @param path 文件路径名称
* @param append 是否以添加的模式写入
* @return 是否写入成功
*/
public static boolean writeFile(byte[] content, String path, boolean append) {
boolean res = false;
File f = new File(path);
RandomAccessFile raf = null;
try {
if (f.exists()) {
if (!append) {
f.delete();
f.createNewFile();
}
} else {
f.createNewFile();
}
if (f.canWrite()) {
raf = new RandomAccessFile(f, "rw");
raf.seek(raf.length());
raf.write(content);
res = true;
}
} catch (Exception e) {
LogUtil.e(e);
} finally {
IOUtils.close(raf);
}
return res;
}
/**
* 把字符串数据写入文件
*
* @param content 需要写入的字符串
* @param path 文件路径名称
* @param append 是否以添加的模式写入
* @return 是否写入成功
*/
public static boolean writeFile(String content, String path, boolean append) {
return writeFile(content.getBytes(), path, append);
}
/**
* 把键值对写入文件
*
* @param filePath 文件路径
* @param key 键
* @param value 值
* @param comment 该键值对的注释
*/
public static void writeProperties(String filePath, String key,
String value, String comment) {
if (StringUtil.isEmpty(key) || StringUtil.isEmpty(filePath)) {
return;
}
FileInputStream fis = null;
FileOutputStream fos = null;
File f = new File(filePath);
try {
if (!f.exists() || !f.isFile()) {
f.createNewFile();
}
fis = new FileInputStream(f);
Properties p = new Properties();
p.load(fis);// 先读取文件,再把键值对追加到后面
p.setProperty(key, value);
fos = new FileOutputStream(f);
p.store(fos, comment);
} catch (Exception e) {
LogUtil.e(e);
} finally {
IOUtils.close(fis);
IOUtils.close(fos);
}
}
/**
* 根据值读取
*/
public static String readProperties(String filePath, String key, String defaultValue) {
if (StringUtil.isEmpty(key) || StringUtil.isEmpty(filePath)) {
return null;
}
String value = null;
FileInputStream fis = null;
File f = new File(filePath);
try {
if (!f.exists() || !f.isFile()) {
f.createNewFile();
}
fis = new FileInputStream(f);
Properties p = new Properties();
p.load(fis);
value = p.getProperty(key, defaultValue);
} catch (IOException e) {
LogUtil.e(e);
} finally {
IOUtils.close(fis);
}
return value;
}
/**
* 把字符串键值对的map写入文件
*/
public static void writeMap(String filePath, Map<String, String> map,
boolean append, String comment) {
if (map == null || map.size() == 0 || StringUtil.isEmpty(filePath)) {
return;
}
FileInputStream fis = null;
FileOutputStream fos = null;
File f = new File(filePath);
try {
if (!f.exists() || !f.isFile()) {
f.createNewFile();
}
Properties p = new Properties();
if (append) {
fis = new FileInputStream(f);
p.load(fis);// 先读取文件,再把键值对追加到后面
}
p.putAll(map);
fos = new FileOutputStream(f);
p.store(fos, comment);
} catch (Exception e) {
LogUtil.e(e);
} finally {
IOUtils.close(fis);
IOUtils.close(fos);
}
}
/**
* 把字符串键值对的文件读入map
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static Map<String, String> readMap(String filePath,
String defaultValue) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
Map<String, String> map = null;
FileInputStream fis = null;
File f = new File(filePath);
try {
if (!f.exists() || !f.isFile()) {
f.createNewFile();
}
fis = new FileInputStream(f);
Properties p = new Properties();
p.load(fis);
map = new HashMap<String, String>((Map) p);// 因为properties继承了map,所以直接通过p来构造一个map
} catch (Exception e) {
LogUtil.e(e);
} finally {
IOUtils.close(fis);
}
return map;
}
/**
* 改名
*/
public static boolean copy(String src, String des, boolean delete) {
File file = new File(src);
if (!file.exists()) {
return false;
}
File desFile = new File(des);
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(file);
out = new FileOutputStream(desFile);
byte[] buffer = new byte[1024];
int count = -1;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
out.flush();
}
} catch (Exception e) {
LogUtil.e(e);
return false;
} finally {
IOUtils.close(in);
IOUtils.close(out);
}
if (delete) {
file.delete();
}
return true;
}
}
Log 日志工具类
import android.util.Log;
public class LogUtil {
private static final String TAG = MyApplication.context.getString(R.string.app_name);
//debug版本是 BuildConfig.DEBUG = true
private static boolean isDebug = BuildConfig.DEBUG;
/**
* 写文件的锁对象
*/
private static final Object mLogLock = new Object();
/**
* 用于记时的变量
*/
private static long mTimestamp = 0;
private static final String LINE_CHAR = "=";
private static final int LENGTH = 80;
private static String LINE;
static {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < LENGTH; i++) {
sb.append(LINE_CHAR);
}
LINE = sb.toString();
}
private LogUtil() {
}
/**
* 把 Log 存储到文件中
*
* @param log 需要存储的日志
* @param path 存储路径
*/
public static void log2File(String log, String path) {
log2File(log, path, true);
}
/**
* 把 Log 存储到文件中
*
* @param log
* @param path
* @param append
*/
public static void log2File(String log, String path, boolean append) {
synchronized (mLogLock) {
FileUtil.writeFile(log + "\r\n", path, append);
}
}
/**
* 打印网络请求错误日志
*
* @param errorMsg
* @param errorCode
*/
private static void printHttpRequestLogError(String errorMsg, int errorCode) {
printLogError("OKHTTP", errorMsg, errorCode);
}
/**
* 打印 list
*
* @param list
* @param <T>
*/
public static <T> void printList(List<T> list) {
if (list == null || list.size() < 1) {
return;
}
int size = list.size();
i("---begin---");
for (int i = 0; i < size; i++) {
i(i + ":" + list.get(i).toString());
}
i("---end---");
}
/**
* 打印 array
*
* @param array
* @param <T>
*/
public static <T> void printArray(T[] array) {
if (array == null || array.length < 1) {
return;
}
int length = array.length;
i("---begin---");
for (int i = 0; i < length; i++) {
i(i + ":" + array[i].toString());
}
i("---end---");
}
/**
* 以级别为 e 的形式输出 msg 信息,附带时间戳,用于输出一个时间段起始点
*
* @param msg
*/
public static void msgStartTime(String msg) {
mTimestamp = System.currentTimeMillis();
if (!TextUtils.isEmpty(msg)) {
e("[Started:" + mTimestamp + "]" + msg);
}
}
/**
* 以级别为 e 的形式输出 msg 信息,附带时间戳,用于输出一个时间段结束点
*
* @param msg
*/
public static void elapsed(String msg) {
long currentTime = System.currentTimeMillis();
long elapsedTime = currentTime - mTimestamp;
mTimestamp = currentTime;
e("[Elapsed:" + elapsedTime + "]" + msg);
}
/**
* 用法:LogUtil.v(msg);
*
* @param msg
*/
public static void v(String msg) {
v(TAG, msg);
}
/**
* 用法:LogUtil.v(tag, msg);
*
* @param tag
* @param msg
*/
public static void v(String tag, String msg) {
print(Log.VERBOSE, tag, msg);
}
/**
* 用法:LogUtil.v(MainActivity.this, msg);
*
* @param object
* @param msg
*/
public static void v(Object object, String msg) {
print(Log.VERBOSE, object.getClass().getSimpleName(), msg);
}
/**
* 用法:LogUtil.d(msg);
*
* @param msg
*/
public static void d(String msg) {
d(TAG, msg);
}
/**
* 用法:LogUtil.d(tag, msg);
*
* @param tag
* @param msg
*/
public static void d(String tag, String msg) {
print(Log.DEBUG, tag, msg);
}
/**
* 用法:LogUtil.d(MainActivity.this, msg);
*
* @param object
* @param msg
*/
public static void d(Object object, String msg) {
print(Log.DEBUG, object.getClass().getSimpleName(), msg);
}
/**
* 用法:LogUtil.i(msg);
*
* @param msg
*/
public static void i(String msg) {
i(TAG, msg);
}
/**
* 用法:LogUtil.i(tag, msg);
*
* @param tag
* @param msg
*/
public static void i(String tag, String msg) {
print(Log.INFO, tag, msg);
}
/**
* 用法:LogUtil.i(MainActivity.this, msg);
*
* @param object
* @param msg
*/
public static void i(Object object, String msg) {
print(Log.INFO, object.getClass().getSimpleName(), msg);
}
/**
* 用法:LogUtil.w(msg);
*
* @param msg
*/
public static void w(String msg) {
w(TAG, msg);
}
/**
* 用法:LogUtil.w(tag, msg);
*
* @param tag
* @param msg
*/
public static void w(String tag, String msg) {
print(Log.WARN, tag, msg);
}
/**
* 用法:LogUtil.w(MainActivity.this, msg);
*
* @param object
* @param msg
*/
public static void w(Object object, String msg) {
print(Log.WARN, object.getClass().getSimpleName(), msg);
}
/**
* 用法:LogUtil.e(msg);
*
* @param msg
*/
public static void e(String msg) {
e(TAG, msg);
}
/**
* 用法:LogUtil.e(tag, msg);
*
* @param tag
* @param msg
*/
public static void e(String tag, String msg) {
print(Log.ERROR, tag, msg);
}
/**
* 用法:LogUtil.e(MainActivity.this, msg);
*
* @param object
* @param msg
*/
public static void e(Object object, String msg) {
print(Log.ERROR, object.getClass().getSimpleName(), msg);
}
/** 以级别为 e 的形式输出Throwable */
public static void e(Throwable tr) {
e("", tr);
}
/** 以级别为 e 的形式输出Throwable */
public static void e(String msg, Throwable tr) {
print(Log.ERROR, TAG, msg, tr);
}
/**
* 用法:LogUtil.wtf(msg);
*
* @param msg
*/
public static void wtf(String msg) {
wtf(TAG, msg);
}
/**
* 用法:LogUtil.wtf(tag, msg);
*
* @param tag
* @param msg
*/
public static void wtf(String tag, String msg) {
print(Log.ASSERT, tag, msg);
}
/**
* 用法:LogUtil.wtf(MainActivity.this, msg);
*
* @param object
* @param msg
*/
public static void wtf(Object object, String msg) {
print(Log.ASSERT, object.getClass().getSimpleName(), msg);
}
/**
* 打印自定义 Log
*
* @param errorMsg
* @param errorCode
*/
public static void printLogError(String errorMsg, int errorCode) {
printLogError(TAG, errorMsg, errorCode);
}
/**
* 打印自定义 Log
*
* @param object
* @param errorMsg
* @param errorCode
*/
public static void printLogError(Object object, String errorMsg, int errorCode) {
printLogError(object.getClass().getSimpleName(), errorMsg, errorCode);
}
/**
* 打印自定义 Log
*
* @param tag
* @param errorMsg
* @param errorCode
*/
public static void printLogError(String tag, String errorMsg, int errorCode) {
e(tag, LINE);//start
e(tag, " 错误信息 ");
e(tag, LINE);//title
e(tag, " ");
e(tag, errorMsg);
e(tag, " ");
e(tag, "错误码: " + errorCode);
e(tag, " ");
e(tag, LINE);//end
}
/**
* 打印 Log
*
* @param level
* @param tag
* @param msg
*/
private static void print(int level, String tag, String msg) {
//不是 debug 模式,则关闭 Log 打印
if (!isDebug) {
return;
}
switch (level) {
case Log.VERBOSE:
Log.v(tag, msg);
break;
case Log.DEBUG:
Log.d(tag, msg);
break;
case Log.INFO:
Log.i(tag, msg);
break;
case Log.WARN:
Log.w(tag, msg);
break;
case Log.ERROR:
Log.e(tag, msg);
break;
case Log.ASSERT:
Log.wtf(tag, msg);
break;
}
}
/**
* 打印 Log
*
* @param level
* @param tag
* @param msg
* @param tr
*/
private static void print(int level, String tag, String msg, Throwable tr) {
//不是 debug 模式,则关闭 Log 打印
if (!isDebug) {
return;
}
switch (level) {
case Log.VERBOSE:
Log.v(tag, msg, tr);
break;
case Log.DEBUG:
Log.d(tag, msg, tr);
break;
case Log.INFO:
Log.i(tag, msg, tr);
break;
case Log.WARN:
Log.w(tag, msg, tr);
break;
case Log.ERROR:
Log.e(tag, msg, tr);
break;
case Log.ASSERT:
Log.wtf(tag, msg, tr);
break;
}
}
}