android通用文件操作
最经用到android的SCCard的文件操作,因此稍作了整理,将它写成一个简单的工具类。其中,可以判断SDCard的是否可用,可用存储空间,文件的创建以及写入数据。经过测试,可以正常使用。代码如下:
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"); } }