1 classFileUtils2 {3 //total number of files under file directory4 Public Static intfilenumber (File dir)5 {6 intFileNumber = 0;7 if(Dir.exists ())8 {9 for(File file:dir.listFiles ())Ten { One if(File.isdirectory ()) A { -FileNumber = filenumber+filenumber (file); - } the Else - { -filenumber++; - } + } - } + returnfilenumber; A } at - //determine if the file is a picture - Public Static Booleanisimage (File imgfilepath) - { - Try - { inFileInputStream Imgfis =NewFileInputStream (imgfilepath); - byte[]imgbyte =New byte[Imgfis.available ()]; to if((Imgfis.read (imgbyte))!=-1) + { - if(Imgbyte[0] = = (byte) ' G ' && imgbyte[1] = = (byte) ' I ' && imgbyte[2] = = (byte) ' F ') the { * return true; $ }Panax Notoginseng Else if(Imgbyte[1] = = (byte) ' P ' && imgbyte[2] = = (byte) ' N ' && imgbyte[3] = = (byte) ' G ') - { the return true; + } A Else if(Imgbyte[6] = = (byte) ' J ' && imgbyte[7] = = (byte) ' F ' && imgbyte[8] = = (byte) ' I ' && imgbyte[9] = = (byte) ' F ') the { + return true; - } $ Else $ { - return false; - } the } -}Catch(Exception e)Wuyi { the System.out.println (e.tostring ()); - return false; Wu } - return false; About } $ - - //returns an array of files for all files in this directory - Public Staticfile[] Listalldirectory (File dir) A { + if(dir!=NULL&&dir.exists ()) the { -File []finalfile =NewFile[filenumber (dir)]; $ intMarkfile =0; the intFileln=0; theFile files[] =dir.listfiles (); the for(inti=0;i<files.length;i++) the { - if(Files[i].isdirectory ()) in { the listalldirectory (Files[i]); the } About Else the { thefinalfile[markfile++]=Files[i]; the } + } - returnFinalfile; the }Bayi Else the { the return NULL; - } - } the the the //copying files (with file channels) the Public Static voidcopyFile (File oldfileabsolutepath,file newfilepath) - { theFile Newfileabsolutepath =NewFile (Newfilepath,oldfileabsolutepath.getname ()); theFileInputStream fi =NULL; theFileOutputStream fo =NULL;94FileChannel in =NULL; theFileChannel out =NULL; the Try { thefi =NewFileInputStream (oldfileabsolutepath);98FO =NewFileOutputStream (newfileabsolutepath); Aboutin =Fi.getchannel (); -out =Fo.getchannel ();101In.transferto (0, In.size (), out);102}Catch(IOException e)103 {104 e.printstacktrace (); the }106 finally107 {108 Try109 { the fi.close ();111 in.close (); the fo.close ();113 out.close (); the}Catch(IOException e) the { the e.printstacktrace ();117 }118 }119 } -}
A simple file toolset for Java