Android common file operations

Source: Internet
Author: User

The most used Android sccard file operations, so I made a little effort to write it into a simple tool class. You can determine whether sdcard is available, available storage space, file creation, and Data Writing. After testing, it can be used normally. The Code is as follows:

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 () {}/ ** <! -- Create and delete file permissions in sdcard --> <uses-Permission * Android: Name = "android. Permission. mount_unmount_filesystems"/> <! -- * Write data permission to 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 sdcardfile pat H = environment. getexternalstoragedirectory (); statfs Sf = new statfs (path. getpath (); // get single block size (byte) Long blocksize = SF. getblocksize (); // obtain the number of all data blocks long allblocks = SF. getblockcount (); // return the SD card size. 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 * block size)/1024; // kb} // ================================== file operation ============== =================== public static Boolean isfileexist (string Director) {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 = 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 + pathfile 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 {tr Y {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 = 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 CacheOS. 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] ;}}

The following code is tested and androidjunittest is used. Of course, you also need the permission to view the operation on sdcard.

1. Configure mainfest. xml of the android project. Note that targetpacket should be consistent with the package name.

// Under the mainfest tag <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> // under the application tag of mainfest <uses-library Android: Name =" android. test. runner "/>

2. Simple test code:

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");}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.