ANDROID对文件的操作
2024-10-12 08:17:36
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import android.os.Environment;
- import android.os.StatFs;
- import android.util.Log;
- public class FileUtil {
- private static int bufferd = 1024;
- private FileUtil() {
- }
- /*
- * <!-- 在SDCard中创建与删除文件权限 --> <uses-permission
- * android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--
- * 往SDCard写入数据权限 --> <uses-permission
- * android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- */
- // =================get SDCard information===================
- public static boolean isSdcardAvailable() {
- String status = Environment.getExternalStorageState();
- if (status.equals(Environment.MEDIA_MOUNTED)) {
- return true;
- }
- return false;
- }
- public static long getSDAllSizeKB() {
- // get path of sdcard
- File path = Environment.getExternalStorageDirectory();
- StatFs sf = new StatFs(path.getPath());
- // get single block size(Byte)
- long blockSize = sf.getBlockSize();
- // 获取所有数据块数
- long allBlocks = sf.getBlockCount();
- // 返回SD卡大小
- return (allBlocks * blockSize) / 1024; // KB
- }
- /**
- * free size for normal application
- *
- * @return
- */
- public static long getSDAvalibleSizeKB() {
- File path = Environment.getExternalStorageDirectory();
- StatFs sf = new StatFs(path.getPath());
- long blockSize = sf.getBlockSize();
- long avaliableSize = sf.getAvailableBlocks();
- return (avaliableSize * blockSize) / 1024;// KB
- }
- // =====================File Operation==========================
- public static boolean isFileExist(String director) {
- File file = new File(Environment.getExternalStorageDirectory()
- + File.separator + director);
- return file.exists();
- }
- /**
- * create multiple director
- *
- * @param path
- * @return
- */
- public static boolean createFile(String director) {
- if (isFileExist(director)) {
- return true;
- } else {
- File file = new File(Environment.getExternalStorageDirectory()
- + File.separator + director);
- if (!file.mkdirs()) {
- return false;
- }
- return true;
- }
- }
- public static File writeToSDCardFile(String directory, String fileName,
- String content, boolean isAppend) {
- return writeToSDCardFile(directory, fileName, content, "", isAppend);
- }
- /**
- *
- * @param director
- * (you don't need to begin with
- * Environment.getExternalStorageDirectory()+File.separator)
- * @param fileName
- * @param content
- * @param encoding
- * (UTF-8...)
- * @param isAppend
- * : Context.MODE_APPEND
- * @return
- */
- public static File writeToSDCardFile(String directory, String fileName,
- String content, String encoding, boolean isAppend) {
- // mobile SD card path +path
- File file = null;
- OutputStream os = null;
- try {
- if (!createFile(directory)) {
- return file;
- }
- file = new File(Environment.getExternalStorageDirectory()
- + File.separator + directory + File.separator + fileName);
- os = new FileOutputStream(file, isAppend);
- if (encoding.equals("")) {
- os.write(content.getBytes());
- } else {
- os.write(content.getBytes(encoding));
- }
- os.flush();
- } catch (IOException e) {
- Log.e("FileUtil", "writeToSDCardFile:" + e.getMessage());
- } finally {
- try {
- if(os != null){
- os.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return file;
- }
- /**
- * write data from inputstream to SDCard
- */
- public File writeToSDCardFromInput(String directory, String fileName,
- InputStream input) {
- File file = null;
- OutputStream os = null;
- try {
- if (createFile(directory)) {
- return file;
- }
- file = new File(Environment.getExternalStorageDirectory()
- + File.separator + directory + fileName);
- os = new FileOutputStream(file);
- byte[] data = new byte[bufferd];
- int length = -1;
- while ((length = input.read(data)) != -1) {
- os.write(data, 0, length);
- }
- // clear cache
- os.flush();
- } catch (Exception e) {
- Log.e("FileUtil", "" + e.getMessage());
- e.printStackTrace();
- } finally {
- try {
- os.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return file;
- }
- /**
- * this url point to image(jpg)
- *
- * @param url
- * @return image name
- */
- public static String getUrlLastString(String url) {
- String[] str = url.split("/");
- int size = str.length;
- return str[size - 1];
- }
- }
下面对代码进行了测试,使用了AndroidJunitTest,当然另外还需要对SDCard查看操作的权限。
1、对android项目的mainfest.xml进行配置,需要注意targetPacket应当与包名保持一致。
- //在mainfest标签下
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
- <instrumentation
- android:name="android.test.InstrumentationTestRunner"
- android:targetPackage="com.example.mygeneralutil" >
- </instrumentation>
- //在mainfest的application标签下
- <uses-library android:name="android.test.runner"/>
2、简单的测试代码如下:
- import android.test.AndroidTestCase;
- import android.util.Log;
- public class FileUtilTest extends AndroidTestCase {
- public void testIsSdcardAvailable() {
- FileUtil.isSdcardAvailable();
- Log.e("FileUtil", ""+FileUtil.isSdcardAvailable());
- }
- public void testGetSDAllSizeKB() {
- FileUtil.getSDAllSizeKB();
- Log.e("FileUtil", ""+(float)FileUtil.getSDAllSizeKB()/1024/1024);
- }
- public void testGetSDAvalibleSizeKB() {
- FileUtil.getSDAvalibleSizeKB();
- Log.e("FileUtil", ""+(float)FileUtil.getSDAvalibleSizeKB()/1024/1024);
- }
- public void testIsFileExist() {
- FileUtil.isFileExist("example");
- Log.e("FileUtil", ""+FileUtil.isFileExist("example"));
- }
- public void testCreateFile() {
- Log.e("FileUtil", ""+FileUtil.createFile("forexample"));
- }
- public void testWriteToSDCardFileStringStringStringBoolean() {
- fail("Not yet implemented");
- }
- public void testWriteToSDCardFileStringStringStringStringBoolean() {
- FileUtil.writeToSDCardFile("forexample", "123.txt",
- "FileUtil.writeToSDCardFile", "utf-8", true);
- }
- public void testWriteToSDCardFromInput() {
- fail("Not yet implemented");
- }
- public void testGetUrlLastString() {
- fail("Not yet implemented");
- }
- }
最新文章
- hibernate与Struts框架结合编写简单针对修改练习
- Devexpress GridView 列中显示图片
- 在浏览器的背后(二) —— HTML语言的语法解析
- Switch语句的case穿透
- python脚本生成exe可执行文件
- C# 属性和索引
- 对话框Dialog
- ES6入门之函数的扩展
- shell脚本操作mysql库
- 【工作记录】android手势事件操作记录
- Android重力感应开发
- Flash AIR 保存与读取
- Socket 基础解析使用ServerSocket建立聊天服务器
- 基于visual Studio2013解决C语言竞赛题之0510求最大和
- Jenkins配置从节点
- 关于easy ui 的combobox遍历选中
- opencv学习之路(28)、轮廓查找与绘制(七)——位置关系及轮廓匹配
- 学会4种备份MySQL数据库(基本备份方面没问题了)
- 《Android进阶之光》--Material Design
- PHP 数据运算类型都有哪些?