在开发Android应用时免不了会跟文件打交道,本篇博文记录总结自己常用到的文件操作代码片段,会不定期总结更新。
删除文件
递归法清除文件
该方法会删除文件以及文件夹下的子文件,类似与linux下的rm -r
效果
public static boolean deleteRecursively(final File path) {
if (path.isDirectory()) {
final File[] files = path.listFiles();
if (files != null) {
for (final File child : files) {
deleteRecursively(child);
}
}
}
return path.delete();
}
清空文件夹
该方法仅仅只是删除文件夹根目录的文件,不会删除子目录,以及子目录下的文件
public static void cleanDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
int count = children.length;
for (int i = 0; i < count; i++) {
File file = new File(dir, children[i]);
if (file.isFile()) {
file.delete();
}
}
}
}
拷贝文件
文件流拷贝
private void copyFile(InputStream source, OutputStream target) throws IOException {
try {
byte[] buffer = new byte[1024];
for (int len = source.read(buffer); len > 0; len = source.read(buffer)) {
target.write(buffer, 0, len);
}
} finally {
if (source != null) {
source.close();
}
if (target != null) {
target.close();
}
}
}
依据文件路径拷贝
/**
* 依据文件路径拷贝
* @param srcPath 源文件
* @param dstPath 目标文件
* @return 拷贝成功true,否则false
*/
public static boolean copyFile(String srcPath, String dstPath) {
boolean result = false;
if ((srcPath == null) || (dstPath == null)) {
return result;
}
File src = new File(srcPath);
File dst = new File(dstPath);
FileChannel srcChannel = null;
FileChannel dstChannel = null;
try {
srcChannel = new FileInputStream(src).getChannel();
dstChannel = new FileOutputStream(dst).getChannel();
srcChannel.transferTo(0, srcChannel.size(), dstChannel);
result = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return result;
} catch (IOException e) {
e.printStackTrace();
return result;
}
try {
srcChannel.close();
dstChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
简洁的renameTo拷贝
该方法需要注意拷贝的源文件与目标文件所在的磁盘文件格式要相同,曾用该方法从内置SD卡往外置SD卡拷贝文件失败,另外文件名也要规范。
public static boolean renameFile(String srcPath, String dstPath) {
boolean result = false;
if ((srcPath == null) || (dstPath == null)) {
return result;
}
File src = new File(srcPath);
File dst = new File(dstPath);
if (src.exists()) {
result = src.renameTo(dst);
}
return result;
}
文件名操作
获取文件名
/**
* 只获取文件名,过滤掉文件路径
*/
public static String getFileName(String absolutePath) {
int sepIndex = absolutePath.lastIndexOf(File.separatorChar);
if (sepIndex >= 0) {
return absolutePath.substring(sepIndex + 1);
}
return absolutePath;
}
获取文件扩展名
/**
* 获取文件扩展名
*
* @param 文件名称,可以带路径
* @return 文件扩展名
*/
public static String getFileExtension(String fileName) {
if (fileName == null) {
return null;
}
String extension = null;
final int lastDot = fileName.lastIndexOf('.');
if ((lastDot >= 0)) {
extension = fileName.substring(lastDot + 1).toLowerCase();
}
return extension;
}
生成副本文件
生成文件的副本,例如传入文件名 “test.txt”, 则生成的副本文件名为”test(1).txt”
/**
* @param 重名的文件名
* @return 新文件名
*/
public static File genrateNextNewName(File file) {
String parentDir = file.getParent();
String fileName = file.getName();
String ext = "";
int newNumber = 0;
if (file.isFile()) {
int extIndex = fileName.lastIndexOf(".");
if (extIndex != -1) {
ext = fileName.substring(extIndex);
fileName = fileName.substring(0, extIndex);
}
}
if (fileName.endsWith(")")) {
int leftBracketIndex = fileName.lastIndexOf("(");
if (leftBracketIndex != -1) {
String numeric = fileName.substring(leftBracketIndex + 1, fileName.length() - 1);
if (numeric.matches("[0-9]+")) {
try {
newNumber = Integer.parseInt(numeric);
newNumber++;
fileName = fileName.substring(0, leftBracketIndex);
} catch (NumberFormatException e) {
System.out.println(e.toString());
}
}
}
}
StringBuffer sb = new StringBuffer();
sb.append(fileName).append("(").append(newNumber).append(")").append(ext);
return new File(parentDir, sb.toString());
}
文件大小换算
将字节大小,换算成大众易理解的KB/MB等单位的大小
/**
*
* @param 字节大小
*/
private static final String UNIT_B = "B";
private static final String UNIT_KB = "KB";
private static final String UNIT_MB = "MB";
private static final String UNIT_GB = "GB";
private static final String UNIT_TB = "TB";
private static final int UNIT_INTERVAL = 1024;
private static final double ROUNDING_OFF = 0.005;
private static final int DECIMAL_NUMBER = 100;
public static String sizeToString(long size) {
String unit = UNIT_B;
if (size < DECIMAL_NUMBER) {
return Long.toString(size) + " " + unit;
}
unit = UNIT_KB;
double sizeDouble = (double) size / (double) UNIT_INTERVAL;
if (sizeDouble > UNIT_INTERVAL) {
sizeDouble = (double) sizeDouble / (double) UNIT_INTERVAL;
unit = UNIT_MB;
}
if (sizeDouble > UNIT_INTERVAL) {
sizeDouble = (double) sizeDouble / (double) UNIT_INTERVAL;
unit = UNIT_GB;
}
if (sizeDouble > UNIT_INTERVAL) {
sizeDouble = (double) sizeDouble / (double) UNIT_INTERVAL;
unit = UNIT_TB;
}
// 0.005 用来舍入.精确到小数点后两位
long sizeInt = (long) ((sizeDouble + ROUNDING_OFF) * DECIMAL_NUMBER);
double formatedSize = ((double) sizeInt) / DECIMAL_NUMBER;
if (formatedSize == 0) {
return "0" + " " + unit;
} else {
return Double.toString(formatedSize) + " " + unit;
}
}
文件压缩
该方法只能对一组文件进行压缩,不能对文件夹进行压缩
/**
* @param 待压缩的文件数组,只能是文件,不能包含文件夹
* @param 生成压缩文件名,例如/local/temp/test.zip
* @throws IOException
*/
public static void zip(String[] files, String zipFile) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(zipFile)));
byte data[] = null;
FileInputStream fi = null;
ZipEntry entry = null;
try {
data = new byte[BUFFER_SIZE];
for (int i = 0; i < files.length; i++) {
fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER_SIZE);
try {
entry = new ZipEntry(files[i].substring(files[i]
.lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
} finally {
entry = null;
origin.close();
origin = null;
}
}
} finally {
fi = null;
data = null;
out.close();
out = null;
}
}