Common tool methods for file operations

Source: Internet
Author: User
Tags readfile string to file

Writing section to file:

/*** Tool method, write bytes to file Delete file if the writing process is abnormal * *@parambytes *@paramfile*/     Public Static voidWritebytestofile (byte[] bytes, file file) {Randomaccessfile Access=NULL; Try{Access=NewRandomaccessfile (file, "RW");        Access.write (bytes); } Catch(IOException e) {if(E.getmessage ()! =NULL) {LOG.E ("JsonUtil2", E.getmessage ());        } file.delete (); } finally{jsonutil.release (access); }    }

bytes of random Read files:

/*** Tool method, random location read bytes of file * *@paramfile *@paramposition *@paramlength *@return     */     Public Static byte[] readFile (File file,intPositionintlength) {        if(File = =NULL|| !file.exists () | | !File.isfile ()) {            return NULL; } randomaccessfile Access=NULL; byte[] bytes =New byte[length]; Try{Access=NewRandomaccessfile (file, "R");            Access.seek (position); Access.readfully (Bytes,0, length); returnbytes; } Catch(Exception e) {if(E.getmessage ()! =NULL) {LOG.E ("JsonUtil2", E.getmessage ()); }            return NULL; } finally{jsonutil.release (access); }    }

Read all bytes of the file:

/*** Tool method, read bytes of file * *@paramfile *@return     */    Private Static byte[] readFile (file file) {if(File = =NULL|| !file.isfile () | | !File.canread ()) {            return NULL; } FileInputStream FIS=NULL; Bufferedinputstream bis=NULL; LongFileSize =file.length (); if(FileSize >integer.max_value) {System.out.println ("File Too big ..."); return NULL; } bytearrayoutputstream Bos=NewBytearrayoutputstream ((int) fileSize); Try{bis=NewBufferedinputstream (Newfileinputstream (file)); intBuf_size = 1024; byte[] buffer =New byte[Buf_size]; intLen = 0;  while( -1! = (len = bis.read (buffer, 0, buf_size))) {bos.write (buffer,0, Len); }            returnBos.tobytearray (); } Catch(IOException e) {LOG.E ("JsonUtil2", "Read bytes form file error"); return NULL; } finally{jsonutil.release (FIS);        Jsonutil.release (bis); }    }

read out the string from the file:

/*** Read the string from the given file * *@paramfile *@returnstring, NULL if the file does not exist*/     Public StaticString readfromfile (file file) {if(File = =NULL|| !file.exists () | | !File.isfile ()) {LOG.E ("Jsonutil", "Cannot read file"); return NULL; } StringBuilder Sbuilder=NewStringBuilder (""); FileReader FR=NULL; BufferedReader BR=NULL; Char[] buffer =New Char[1024]; intLength =-1; Try{FR=Newfilereader (file); BR=NewBufferedReader (FR);  while(length = br.read (buffer))! =-1) {sbuilder.append (buffer,0, length); }        } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally{Release (FR);        Release (BR); }        if(sbuilder.length () = = 0) {//if the length after reading is still zero            return NULL; }        //log.i ("bbbbb", "" +sbuilder.tostring ());//Test        /*** To determine if the first char is not a UTF8 BOM file header If yes, remove the first char*/        if(Getthechar (). Equals (((Character) (Sbuilder.charat (0))) {Sbuilder.deletecharat (0); }        returnsbuilder.tostring (); }

Release closable Resources:

 /**   * release closable resources * *   @param   closeobj  */
     public  static  void   release (closeable closeobj) {  If  (closeobj! = null  ) { try   {closeobj.close ();  catch   (IOException e) {e.printst            Acktrace ();        } closeobj  = null  ; }    }

Write String to file:

/*** Writes the specified string to the specified file, overwriting write * *@paramfile *@paramSTR *@param Cover * Overwrite write, true overwrite, false append*/    Private Static voidwritetofile (file file, String str, Boolean cover) {cover= !cover; if(File = =NULL|| !file.exists () | | !File.isfile ()) {LOG.E ("Jsonutil", "Cannot write file"); return; }        if(str = =NULL) {            return; } FileWriter FW=NULL; BufferedWriter BW=NULL; Try{FW=NewFileWriter (file, cover); Bw=NewBufferedWriter (FW); //log.e ("Jsonutil", File.getabsolutepath ());bw.write (str);        Bw.flush (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally{release (FW);        Release (BW); }    }

Utf-8 file header with BOM:

/*** Get UTF8 file header char * *@return     */    Private StaticCharacter Getthechar () {byteA = (byte) 239;//0xEF (byte) 0xef;eb        byteB = (byte) 187;//(byte) 0XBB;BC        bytec = (byte) 191;//0xbf;80//char ret =//( Char) (((A&0X000000FF) <<24) | ( B&0X000000FF) <<16|        (C&0X000000FF) <<8|0x00000000); //return (Character) ret;        Char[] chars = GetChars (New byte[] {A, B, C}); return(Character) Chars[0]; }    /*** bytes Turn chars * *@parambytes *@return     */    Private Static Char[] GetChars (byte[] bytes) {Charset cs= Charset.forname ("UTF-8"); Bytebuffer BB=bytebuffer.allocate (bytes.length);        Bb.put (bytes);        Bb.flip (); Charbuffer CB=Cs.decode (BB); returnCb.array (); }

Common tool methods for file operations

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.