1 class FileUtils 2 { 3 //文件目录下文件总数目 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 //判断文件是否为图片 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 //返回该目录下所有文件的文件数组 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 //复制文件(用文件通道) 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 finally 107 { 108 try 109 { 110 fi.close(); 111 in.close(); 112 fo.close(); 113 out.close(); 114 } catch (IOException e) 115 { 116 e.printStackTrace(); 117 } 118 } 119 } 120 }