标签:
class FileUtils
{
//文件目录下文件总数目
public static int fileNumber(File dir)
{
int filenumber = 0;
if(dir.exists())
{
for(File file:dir.listFiles())
{
if(file.isDirectory())
{
filenumber = filenumber+fileNumber(file);
}
else
{
filenumber++;
}
}
}
return filenumber;
}
//判断文件是否为图片
public static boolean isImage(File imgFilePath)
{
try
{
FileInputStream imgfis = new FileInputStream(imgFilePath);
byte []imgbyte = new byte[imgfis.available()];
if((imgfis.read(imgbyte))!=-1)
{
if(imgbyte[0] == (byte) ‘G‘ && imgbyte[1] == (byte) ‘I‘ && imgbyte[2] == (byte) ‘F‘)
{
return true;
}
else if(imgbyte[1] == (byte) ‘P‘ && imgbyte[2] == (byte) ‘N‘ && imgbyte[3] == (byte) ‘G‘)
{
return true;
}
else if(imgbyte[6] == (byte) ‘J‘ && imgbyte[7] == (byte) ‘F‘ && imgbyte[8] == (byte) ‘I‘&& imgbyte[9] == (byte) ‘F‘)
{
return true;
}
else
{
return false;
}
}
}catch(Exception e)
{
System.out.println(e.toString());
return false;
}
return false;
}
//返回该目录下所有文件的文件数组
public static File[] listAllDirectory(File dir)
{
if(dir!=null&&dir.exists())
{
File []finalfile = new File[fileNumber(dir)];
int markfile =0;
int fileln=0;
File files[] = dir.listFiles();
for(int i=0;i<files.length;i++)
{
if(files[i].isDirectory())
{
listAllDirectory(files[i]);
}
else
{
finalfile[markfile++]=files[i];
}
}
return finalfile;
}
else
{
return null;
}
}
//复制文件(用文件通道)
public static void copyFile(File oldFileAbsolutePath,File newFilePath)
{
File newFileAbsolutePath = new File(newFilePath,oldFileAbsolutePath.getName());
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
try {
fi = new FileInputStream(oldFileAbsolutePath);
fo = new FileOutputStream(newFileAbsolutePath);
in = fi.getChannel();
out = fo.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
fi.close();
in.close();
fo.close();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/shouce/p/5108261.html