Java: A simple file toolkit and a java toolkit
1 class FileUtils 2 {3 // total number of files in the File directory 4 public static int fileNumber (File dir) 5 {6 int filenumber = 0; 7 if (dir. exists () 8 {9 for (File file: dir. listFiles () 10 {11 if (file. isDirectory () 12 {13 filenumber = filenumber + fileNumber (file); 14} 15 else 16 {17 filenumber ++; 18} 19} 20} 21 return filenumber; 22} 23 24 // determine whether the File is an image 25 public static boolean isImage (File imgFilePath) 26 {27 try 28 {29 FileInputStream imgfis = new FileInputStream (imgFilePath); 30 byte [] imgbyte = new byte [imgfis. available ()]; 31 if (imgfis. read (imgbyte ))! =-1) 32 {33 if (imgbyte [0] = (byte) 'G' & imgbyte [1] = (byte) 'I' & imgbyte [2] = (byte) 'F') 34 {35 return true; 36} 37 else if (imgbyte [1] = (byte) 'P' & imgbyte [2] = (byte) 'n' & imgbyte [3] = (byte) 'G') 38 {39 return true; 40} 41 else if (imgbyte [6] = (byte) 'J' & imgbyte [7] = (byte) 'F' & imgbyte [8] = (byte) 'I' & imgbyte [9] = (byte) 'F') 42 {43 return true; 44} 45 else 46 {47 return false; 48} 49} 50} catch (Exception e) 51 {52 System. out. println (e. toString (); 53 return false; 54} 55 return false; 56} 57 58 59 // returns the array of all files in the directory 60 public static File [] listAllDirectory (File dir) 61 {62 if (dir! = Null & dir. exists () 63 {64 File [] finalfile = new File [fileNumber (dir)]; 65 int markfile = 0; 66 int fileln = 0; 67 File files [] = dir. listFiles (); 68 for (int I = 0; I <files. length; I ++) 69 {70 if (files [I]. isDirectory () 71 {72 listAllDirectory (files [I]); 73} 74 else 75 {76 finalfile [markfile ++] = files [I]; 77} 78} 79 return finalfile; 80} 81 else 82 {83 return null; 84} 85} 86 87 88 // copy the file (using the file channel) 89 public static void copyFile (File oldFileAbsolutePath, File newFilePath) 90 {91 File newFileAbsolutePath = new File (newFilePath, oldFileAbsolutePath. getName (); 92 FileInputStream fi = null; 93 FileOutputStream fo = null; 94 FileChannel in = null; 95 FileChannel out = null; 96 try {97 fi = new FileInputStream (oldFileAbsolutePath); 98 fo = new FileOutputStream (newFileAbsolutePath); 99 in = fi. getChannel (); 100 out = fo. getChannel (); 101 in. transferTo (0, in. size (), out); 102} catch (IOException e) 103 {104 e. printStackTrace (); 105} 106 finally107 {108 try109 {110 fi. close (); 111 in. close (); 112 fo. close (); 113 out. close (); 114} catch (IOException e) 115 {116 e. printStackTrace (); 117} 118} 119} 120}