1,修改文件名称
/**
* 文件重命名
*
* @description:
* @author ldm
* @date 2016-6-12 下午3:20:30 参数: File f:要重命名的文件 String newName:新名称
*/
private void reNameForFile(File f, String newName) {
if (TextUtils.isEmpty(newName) || newName.equals(f.getName()))
return;
try {
File newf = new File(f.getParent(), newName);
if (newf.exists()) {
Toast.makeText(getActivity(), "文件已经存在!", Toast.LENGTH_LONG)
.show();
} else if (f.renameTo(newf)) {
Toast.makeText(getActivity(), "重命名成功!", Toast.LENGTH_LONG)
.show();
}
} catch (SecurityException se) {
Toast.makeText(getActivity(), "重命名失败!", Toast.LENGTH_LONG).show();
}
}
2,计算SD卡剩余容量:
/**
* 显示SD卡可用空间
*
* @description:
* @author ldm
* @date 2016-6-12 下午3:06:42
*/
@SuppressWarnings("deprecation")
public static String calSdCardAvailable() {
String result = "";
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
// StatFs类主要用来获取文件系统的状态
StatFs stf = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
long blockSize = stf.getBlockSize();// block大小
long blockCount = stf.getBlockCount();// bloc数目
long availCount = stf.getAvailableBlocks();// 总大小
return calFileSize(availCount * blockSize) + " / "
+ calFileSize(blockSize * blockCount);
}
return result;
}
----------
/**
* 计算文件大小
*
* @description:
* @author ldm
* @date 2016-6-12 下午3:11:46
*/
public static String calFileSize(long size) {
String fileSize;
if (size < KB)
fileSize = size + "B";
else if (size < MB)
fileSize = String.format("%.1f", size / KB) + "KB";
else if (size < GB)
fileSize = String.format("%.1f", size / MB) + "MB";
else
fileSize = String.format("%.1f", size / GB) + "GB";
return fileSize;
}
3,多个SD卡时 取外置SD卡 ,代码来自网友项目
/** 多个SD卡时 取外置SD卡 */
public static String getExternalStorageDirectory() {
// 参考文章
// http://blog.youkuaiyun.com/bbmiku/article/details/7937745
Map<String, String> map = System.getenv();
String[] values = new String[map.values().size()];
map.values().toArray(values);
String path = values[values.length - 1];
if (path.startsWith("/mnt/")
&& !Environment.getExternalStorageDirectory().getAbsolutePath()
.equals(path))
return path;
else
4,文件复制
/**
* @description 复制文件
* @author ldm
* @time 2016/6/12 15:30
* @param
*/
public static void copyFile(File from, File to) {
if (null == from || !from.exists()) {
return;
}
if (null == to) {
return;
}
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream(from);
if (!to.exists()) {
to.createNewFile();
}
os = new FileOutputStream(to);
copyFileFast(is, os);
} catch (Exception e) {
throw new KJException(FileUtil.class.getClass().getName(), e);
} finally {
closeIO(is, os);
}
}
5,删除文件
/**
* @description 删除文件
* @author ldm
* @time 2016/6/12 15:30
* @param
*/
public static void delFile(File file) {
if (file.exists()) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
clear(f);
file.delete();
}
}
else {
file.delete();
}
}
}