/**
* rl 2018/07/14
* 自定义文件类
* 处理文件操作
*/
public class FileUtils {
private static String TAG = "FileUtils";
/**
* 读取文件操作
*
* @param filepath 文件路径 : 例: /sdcard/download/001.txt
* @return 返回文件的byte[]值
*/
public static byte[] readFileTobyte(String filepath) {
if(isExists(filepath)) {
LogUtils.i(TAG,"文件不存在!");
return null;
}
byte[] buf = new byte[(int) new File(filepath).length()];
try {
FileInputStream inputStream = new FileInputStream(filepath);
int len = inputStream.read(buf);
inputStream.close();
LogUtils.i(TAG, "文件长度" + len);
} catch (java.io.IOException e) {
LogUtils.e(TAG, "文件读取异常 :" + e);
}
return buf;
}
/**
* 读取文件转换为string
* @param filepath 文件路径
* @return string
*/
public static String readFileToString(String filepath) {
if(isExists(filepath)) {
LogUtils.i(TAG,"文件不存在!");
return null;
}
StringBuilder str = new StringBuilder("");
byte[] buf = new byte[(int) new File(filepath).length()];
try {
FileInputStream inputStream = new FileInputStream(filepath);
if (inputStream.read(buf) > 0) {
str.append(Arrays.toString(buf));
}
inputStream.close();
} catch (IOException e) {
LogUtils.e(TAG, "文件读取错误 :" + e);
}
return String.valueOf(str);
}
/**
* 写入文件
*
* @param filename 文件名:/sdcard/1.txt/
* @param content 写入内容
* @return 0:写入失败,1:写入成功
*/
public static int writeFile(String filename, String content) {
int success = 0;
try {
FileOutputStream fileOutputStream = new FileOutputStream(filename);
fileOutputStream.write(content.getBytes());
success = 1;
fileOutputStream.close();
} catch (IOException e) {
success = 0;
LogUtils.e("文件写入错误 :" + e);
}
return success;
}
/**
* 写入文件
* @param filename 文件名
* @param buf 文件byte[]
* @return 0失败,1成功
*/
public static int writeFile(String filename, byte[] buf) {
int success = 0;
try {
FileOutputStream fileOutputStream = new FileOutputStream(filename);
fileOutputStream.write(buf);
success = 1;
fileOutputStream.close();
} catch (IOException e) {
success = 0;
LogUtils.e(TAG, "文件写入错误" + e);
}
return success;
}
/**
* 判断文件或文件夹是否存在
* @param filepath 文件路径
* @return
*/
private static boolean isExists(String filepath){
File file = new File(filepath);
if(file.exists()){
return true;
}
return false;
}
}
自定义文件读写utils类
最新推荐文章于 2024-05-11 11:17:25 发布