您的位置:首页 > 移动开发 > Android开发

【android 文件的基本操作】

2016-11-30 10:28 316 查看
在此总结一下文件的基本操作。

先把一些常用的方法,封装一下,我这些都放到 FileUtils.java 类中:

/**
* 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.mContext.getExternalCacheDir().getPath();
} else {
// /data/data/<application package>/cache
cacheRootPath = MyApplication.mContext.getCacheDir().getPath();
}
return cacheRootPath;
}

/**
* 创建文件夹
*
* @param dirPath
* @return 创建失败返回""
*/
public 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;
}

/**
* 创建文件
* 文件路径为根路径:/storage/emulated/0/Android/data/<application package>/cache
*/
public static boolean createFile(Context context, String uniqueName) {
File file = getDiskCacheDir(context, uniqueName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

/**
* 往文件中储存内容,根据文件路径,这个方法更严谨一些
*
* @param content
* @param filePath
* @return
*/
public static boolean saveStringToFile(String content, String filePath) {
if (content == null || TextUtils.isEmpty(filePath)) {
return false;
} else {
File file = new File(filePath);
PrintWriter pw = null;
try {
if (!file.exists()) {
file.createNewFile();
}
if (file.exists()) {
pw = new PrintWriter(file);
// pw = new PrintWriter(new BufferedWriter(
// new FileWriter(file)));
pw.write(content);
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
} finally {
if (pw != null) {
pw.close();
}
}

}
}

/**
* 读取文件中的内容,根据文件路径
*
* @param filePath
* @return
*/
@SuppressWarnings("resource")
public static String readStringFromFile(String filePath) {
if (TextUtils.isEmpty(filePath)) {
return null;
}
File file = new File(filePath);
if (file.exists()) {
try {

StringBuffer strBuffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(file));
String strLine = "";
while ((strLine = reader.readLine()) != null) {
strBuffer.append(strLine);
}
return strBuffer.toString();
} catch (Exception e) {
return null;
}
} else {
return null;
}
}

/**
* 根据传进的 file 删除文件或者文件夹
*
* @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();
}
}

/**
* 根据传进的 filePath 删除文件或者文件夹
*
* @param filePath
* @return boolean
*/
public static boolean deleteFileOrDirectory(String filePath) {

if (TextUtils.isEmpty(filePath)) {
return false;
} else {
try {
File file = new File(filePath);
if (file.isFile()) {
file.delete();
return true;
}
if (file.isDirectory()) {
File[] childFiles = file.listFiles();
// 删除空文件夹
if (childFiles == null || childFiles.length == 0) {
file.delete();
return true;
}
// 递归删除文件夹下的子文件
for (int i = 0; i < childFiles.length; i++) {
deleteFileOrDirectory(childFiles[i]);
}
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}

/**
* 将内容写入文件
*
* @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();

}
}

/**
* 根据传入的文件名字,在根缓存目录下创建文件,并返回该文件对象
*
* @param context
* @param uniqueName
* @return
*/
public static File getDiskCacheDir(Context context, String uniqueName) {
final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ? getExternalCacheDir(context).getPath() : context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}

public static File getExternalCacheDir(Context context) {
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}

/**
* 获取图片缓存目录
*
* @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;
}


有个这个工具类,就可以对文件做一些基本的操作了!

在应用根缓存目录下或者在某某目录下实现如下操作:创建一个文件夹 ——>文件夹中创建一个文件 ——> 往文件中写入内容 ——> 读取内容 ——> 删除该文件 ——> 删除该文件夹 。

(1)创建一个文件夹

public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivityfile";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/**
* 创建 log 文件夹
*/
String folderPath = FileUtils.createDir("data/data/" + getPackageName() + "/log");
Log.i(TAG, "onCreate: folderPath=" + folderPath);

}
}


adb查看如下:



(2)文件夹中创建一个文件

/**
* 创建 info 文件,在 log 文件夹中
*/
File file = new File(folderPath, "/info");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}


adb查看如下:



(3) 往文件中写入内容

/**
*   往文件中写入内容
*/
boolean saveResult = FileUtils.saveStringToFile("我是来记录info级别的日志", folderPath + "/info");
Log.i(TAG, "onCreate: saveResult=" + saveResult);


adb命令 pull 下来如下:





(4) 读取文件内容

/**
*  读取内容
*/
String fileContext = FileUtils.readStringFromFile(folderPath + "/info");
Log.i(TAG, "onCreate: fileContext=" + fileContext);


日志打印:



(5)删除该文件

/**
*  删除该文件
*/
//FileUtils.deleteFileOrDirectory(file);
boolean deleteResult = FileUtils.deleteFileOrDirectory(folderPath + "/info");
Log.i(TAG, "onCreate: deleteResult=" + deleteResult);


日志打印:



adb查看发现:log 文件夹下已经没有 info 文件了:



(6) 删除该文件夹

/**
* 删除该文件夹
*/
boolean deleteDirectoryResult = FileUtils.deleteFileOrDirectory(folderPath);
Log.i(TAG, "onCreate: deleteDirectoryResult=" + deleteDirectoryResult);


日志打印:



adb查看,log 文件夹已经没有了:



总结:到这里对文件的基本操作,基本完成了。下面,希望我继续挤出时间,去总结对 文件 的上传,下载的运用。

源码下载地址

注意:源码中看app2这个module
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: