Android file read/write tool class

Source: Internet
Author: User

I write the tool class, write bad, slowly modify.

Remember to add permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

 PackageCom.sy.utils;ImportAndroid.content.Context;ImportAndroid.os.Environment;ImportAndroid.os.StatFs;ImportAndroid.util.Log;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;/** * Created by SY on 2016/5/9. * File read/write tool class */ Public  class FileUtils {    PrivateContext context;PrivateString Sdcardpath = Environment.getexternalstoragedirectory (). GetAbsolutePath ();//SD Card Path    Private StaticString sdstate = Environment.getexternalstoragestate ();//SD card Status     Public FileUtils(Context context) { This. Context = Context; }/** * file stored in/data/data/<packagename>/files/default directory * * @param fileName * @param b Ytes * @return * *     Public Boolean Write2cachefile(String FileName,byte[] bytes) {FileOutputStream out =NULL; Bufferedoutputstream BOS =NULL;Try{out = Context.openfileoutput (FileName, context.mode_private); BOS =NewBufferedoutputstream (out);            Bos.write (bytes); Bos.flush ();return true; }Catch(Exception e)        {E.printstacktrace (); }finally{if(Bos! =NULL) {Try{Bos.close (); }Catch(IOException e)                {E.printstacktrace (); }            }        }return false; }/** * Write bytes to sd card * * @param path folder directory * @param File file name * @param Data Write The byte array * @return * /     Public Static Boolean writebytes(string path, string file,byte[] data) {FileOutputStream FOS =NULL;Try{//have sufficient capacity            if(Data.length < Getsdfreesize ())                {createdirectoryifnotexist (path);                Createfileifnotexist (path + file); FOS =NewFileOutputStream (path + file.separator + File);                Fos.write (data); Fos.flush ();return true; }        }Catch(Exception e) {LOG.E ("Writebytes", E.getmessage ()); }finally{if(Fos! =NULL) {Try{Fos.close (); }Catch(IOException e)                {E.printstacktrace (); }            }return false; }    }/** * Read byte array from SD card * * @param Path directory * @param filename * @return  return byte array, file does not exist return NULL * /     Public Static byte[]readbytes(string path, String fileName) {File File =NewFile (path + file.separator + fileName);if(!file.exists ()) {return NULL; } InputStream InputStream =NULL;Try{InputStream =NewBufferedinputstream (NewFileInputStream (file));byte[] data =New byte[Inputstream.available ()]; Inputstream.read (data);returnData }Catch(IOException e)        {E.printstacktrace (); }finally{Try{if(InputStream! =NULL) {inputstream.close (); }            }Catch(IOException e)            {E.printstacktrace (); }        }return NULL; }/** * Writes a byte stream to the SD card file * * @param Path directory path * @param filename * @param input byte stream * @return * /     Public StaticBooleanWrite2sdfrominput(string path, string fileName, InputStream input) {File File =NULL; OutputStream output =NULL;Try{intSize = Input.available ();//have sufficient capacity            if(Size < Getsdfreesize ())                {createdirectoryifnotexist (path);                Createfileifnotexist (path + file.separator + fileName); File =NewFile (path + file.separator + fileName); Output =NewBufferedoutputstream (NewFileOutputStream (file));byteBuffer[] =New byte[1024x768];intTemp while(temp = input.read (buffer))! =-1) {output.write (buffer,0, temp); } output.flush ();return true; }        }Catch(IOException E1)        {E1.printstacktrace (); }finally{Try{if(Output! =NULL) {output.close (); }            }Catch(Exception e)            {E.printstacktrace (); }        }return false; }/** * Determine if the SD card exists * * @ return * *    Private Static Boolean sdcardisexist() {if(Sdstate.equals (environment.media_mounted)) {return true; }Else            return false; }/** * Get SD card remaining capacity size (in bytes) * * @return */     Public Static Long getsdfreesize() {//Get SD card file pathFile path = Environment.getexternalstoragedirectory (); StatFs SF =NewStatFs (Path.getpath ());//Gets the size of a single data block (Byte)        LongBlockSize = Sf.getblocksize ();//number of idle data blocks        LongFreeblocks = Sf.getavailableblocks ();//Return SD card idle size        returnFreeblocks * BLOCKSIZE;//Unit byte        //return (freeblocks * blockSize)/1024; Unit KB//Return (Freeblocks * blockSize)/1024/1024;//unit MB}/** * Get SD card Total capacity size (in bytes) * * @return */     Public Static Long getsdallsize() {//Get SD card file pathFile path = Environment.getexternalstoragedirectory (); StatFs SF =NewStatFs (Path.getpath ());//Gets the size of a single data block (Byte)        LongBlockSize = Sf.getblocksize ();//Get the number of all data blocks        LongAllblocks = Sf.getblockcount ();//Return SD card size        returnAllblocks * BLOCKSIZE;//Unit byte        //return (allblocks * blockSize)/1024;//unit KB//Return (Allblocks * blockSize)/1024/1024;//unit MB}/** * If directory does not exist, create directory * * @param Path directory * @return  */     Public Static Boolean createdirectoryifnotexist(String Path) {File File =NewFile (path);//If the folder does not exist, create        if(!file.exists () &&!file.isdirectory ()) {returnFile.mkdirs (); }Else{LOG.E ("Catalog","Directory exists!" ");return false; }    }/** * If the file does not exist, create the file * @param Path File * * @return * /     Public Static Boolean createfileifnotexist(String Path) {File File =NewFile (path);Try{if(!file.exists ()) {returnFile.createnewfile (); }Else{LOG.E ("File","File exists! ");return false; }        }Catch(Exception e) {LOG.E ("Error", E.getmessage ());return false; }    }}

Android file read/write tool class

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.