- packagecom.work.util;
- importjava.io.BufferedInputStream;
- importjava.io.BufferedOutputStream;
- importjava.io.BufferedReader;
- importjava.io.BufferedWriter;
- importjava.io.File;
- importjava.io.FileInputStream;
- importjava.io.FileNotFoundException;
- importjava.io.FileOutputStream;
- importjava.io.IOException;
- importjava.io.InputStreamReader;
- importjava.io.OutputStreamWriter;
- importjava.io.RandomAccessFile;
- importjava.io.StringReader;
- importjava.util.ArrayList;
- importjava.util.List;
- importjava.util.zip.ZipEntry;
- importjava.util.zip.ZipOutputStream;
- importorg.apache.commons.logging.Log;
- importorg.apache.commons.logging.LogFactory;
- /**
- *日期:2008-2-1412:05:18<br/>
- *project:zxj<br/>
- *作者:wangmingjie<br/>
- */
- publicclassFileUtil{
- privatestaticLoglog=LogFactory.getLog(FileUtil.class);
- /**
- *创建单个文件夹。
- *
- *@paramdir
- *@paramignoreIfExitst
- *true表示如果文件夹存在就不再创建了。false是重新创建。
- *@throwsIOException
- */
- publicstaticvoidcreateDir(Stringdir,booleanignoreIfExitst)
- throwsIOException{
- Filefile=newFile(dir);
- if(ignoreIfExitst&&file.exists()){
- return;
- }
- if(file.mkdir()==false){
- thrownewIOException("Cannotcreatethedirectory="+dir);
- }
- }
- /**
- *创建多个文件夹
- *
- *@paramdir
- *@paramignoreIfExitst
- *@throwsIOException
- */
- publicstaticvoidcreateDirs(Stringdir,booleanignoreIfExitst)
- throwsIOException{
- Filefile=newFile(dir);
- if(ignoreIfExitst&&file.exists()){
- return;
- }
- if(file.mkdirs()==false){
- thrownewIOException("Cannotcreatedirectories="+dir);
- }
- }
- /**
- *删除一个文件。
- *
- *@paramfilename
- *@throwsIOException
- */
- publicstaticvoiddeleteFile(Stringfilename)throwsIOException{
- Filefile=newFile(filename);
- log.trace("Deletefile="+filename);
- if(file.isDirectory()){
- thrownewIOException(
- "IOException->BadInputException:notafile.");
- }
- if(file.exists()==false){
- thrownewIOException(
- "IOException->BadInputException:fileisnotexist.");
- }
- if(file.delete()==false){
- thrownewIOException("Cannotdeletefile.filename="+filename);
- }
- }
- /**
- *删除文件夹及其下面的子文件夹
- *
- *@paramdir
- *@throwsIOException
- */
- publicstaticvoiddeleteDir(Filedir)throwsIOException{
- if(dir.isFile())
- thrownewIOException(
- "IOException->BadInputException:notadirectory.");
- File[]files=dir.listFiles();
- if(files!=null){
- for(inti=0;i<files.length;i++){
- Filefile=files[i];
- if(file.isFile()){
- file.delete();
- }else{
- deleteDir(file);
- }
- }
- }//if
- dir.delete();
- }
- publicstaticStringgetPathSeparator(){
- returnjava.io.File.pathSeparator;
- }
- publicstaticStringgetFileSeparator(){
- returnjava.io.File.separator;
- }
- /**
- *列出指定文件目录下面的文件信息。
- *
- *@paramdir
- *@return
- *@throwsIOException
- */
- publicstaticList<FileInfo>getFiles(Filedir)throwsIOException{
- if(dir.isFile())
- thrownewIOException("BadInputException:notadirectory.");
- if(!dir.exists()){
- thrownewIOException("don'texist");
- }
- File[]files=dir.listFiles();
- intLEN=0;
- if(files!=null){
- LEN=files.length;
- }
- List<FileInfo>l=newArrayList<FileInfo>();
- longtempFLen=0;//文件长度
- for(inti=0;i<LEN;i++){
- FileInfotemp=newFileInfo();
- temp.setFileName(files[i].getName());
- temp.setIsDir(files[i].isDirectory());
- //是文件,且包含.
- if(files[i].isFile()){
- if(files[i].getName().lastIndexOf(".")!=-1)
- temp.setFileType(files[i].getName().substring(
- files[i].getName().lastIndexOf(".")));
- }else{
- temp.setFileType("文件夹");
- }
- tempFLen=files[i].length();
- temp.setFileLen(tempFLen);
- if(tempFLen/1024/1024/1024>0){
- temp.setFileLength(files[i].length()/1024/1024/1024+"G");
- }elseif(tempFLen/1024/1024>0){
- temp.setFileLength(files[i].length()/1024/1024+"M");
- }elseif(tempFLen/1024>0){
- temp.setFileLength(files[i].length()/1024+"K");
- }else{
- temp.setFileLength(tempFLen+"byte");
- }
- temp.setFilePath(files[i].getAbsolutePath().replaceAll("[\\\\]","/"));
- temp.setLastModifiedTime(com.work.util.DateUtil
- .getDateTime(files[i].lastModified()));
- temp.setIsHidden(files[i].isHidden());
- temp.setAuthor(null);
- temp.setVersion(null);
- temp.setFileClass(null);
- temp.setRemark(null);
- l.add(temp);
- }
- returnl;
- }
- /**
- *获取到目录下面文件的大小。包含了子目录。
- *
- *@paramdir
- *@return
- *@throwsIOException
- */
- publicstaticlonggetDirLength(Filedir)throwsIOException{
- if(dir.isFile())
- thrownewIOException("BadInputException:notadirectory.");
- longsize=0;
- File[]files=dir.listFiles();
- if(files!=null){
- for(inti=0;i<files.length;i++){
- Filefile=files[i];
- //file.getName();
- //System.out.println(file.getName());
- longlength=0;
- if(file.isFile()){
- length=file.length();
- }else{
- length=getDirLength(file);
- }
- size+=length;
- }//for
- }//if
- returnsize;
- }
- /**
- *将文件清空。
- *
- *@paramsrcFilename
- *@throwsIOException
- */
- publicstaticvoidemptyFile(StringsrcFilename)throwsIOException{
- FilesrcFile=newFile(srcFilename);
- if(!srcFile.exists()){
- thrownewFileNotFoundException("Cannotfindthefile:"
- +srcFile.getAbsolutePath());
- }
- if(!srcFile.canWrite()){
- thrownewIOException("Cannotwritethefile:"
- +srcFile.getAbsolutePath());
- }
- FileOutputStreamoutputStream=newFileOutputStream(srcFilename);
- outputStream.close();
- }
- /**
- *WritecontenttoafileNamewiththedestEncoding写文件。如果此文件不存在就创建一个。
- *
- *@paramcontent
- *String
- *@paramfileName
- *String
- *@paramdestEncoding
- *String
- *@throwsFileNotFoundException
- *@throwsIOException
- */
- publicstaticvoidwriteFile(Stringcontent,StringfileName,
- StringdestEncoding)throwsFileNotFoundException,IOException{
- Filefile=null;
- try{
- file=newFile(fileName);
- if(!file.exists()){
- if(file.createNewFile()==false){
- thrownewIOException("createfile'"+fileName
- +"'failure.");
- }
- }
- if(file.isFile()==false){
- thrownewIOException("'"+fileName+"'isnotafile.");
- }
- if(file.canWrite()==false){
- thrownewIOException("'"+fileName+"'isaread-onlyfile.");
- }
- }finally{
- //wedonthavetocloseFilehere
- }
- BufferedWriterout=null;
- try{
- FileOutputStreamfos=newFileOutputStream(fileName);
- out=newBufferedWriter(newOutputStreamWriter(fos,destEncoding));
- out.write(content);
- out.flush();
- }catch(FileNotFoundExceptionfe){
- log.error("Error",fe);
- throwfe;
- }catch(IOExceptione){
- log.error("Error",e);
- throwe;
- }finally{
- try{
- if(out!=null)
- out.close();
- }catch(IOExceptionex){
- }
- }
- }
- /**
- *读取文件的内容,并将文件内容以字符串的形式返回。
- *
- *@paramfileName
- *@paramsrcEncoding
- *@return
- *@throwsFileNotFoundException
- *@throwsIOException
- */
- publicstaticStringreadFile(StringfileName,StringsrcEncoding)
- throwsFileNotFoundException,IOException{
- Filefile=null;
- try{
- file=newFile(fileName);
- if(file.isFile()==false){
- thrownewIOException("'"+fileName+"'isnotafile.");
- }
- }finally{
- //wedonthavetocloseFilehere
- }
- BufferedReaderreader=null;
- try{
- StringBufferresult=newStringBuffer(1024);
- FileInputStreamfis=newFileInputStream(fileName);
- reader=newBufferedReader(newInputStreamReader(fis,srcEncoding));
- char[]block=newchar[512];
- while(true){
- intreadLength=reader.read(block);
- if(readLength==-1)
- break;//endoffile
- result.append(block,0,readLength);
- }
- returnresult.toString();
- }catch(FileNotFoundExceptionfe){
- log.error("Error",fe);
- throwfe;
- }catch(IOExceptione){
- log.error("Error",e);
- throwe;
- }finally{
- try{
- if(reader!=null)
- reader.close();
- }catch(IOExceptionex){
- }
- }
- }
- /*
- *1ABC2abCGiasudoctudong1laycathay5dong=>1-->53ABC
- */
- publicstaticString[]getLastLines(Filefile,intlinesToReturn)
- throwsIOException,FileNotFoundException{
- finalintAVERAGE_CHARS_PER_LINE=250;
- finalintBYTES_PER_CHAR=2;
- RandomAccessFilerandomAccessFile=null;
- StringBufferbuffer=newStringBuffer(linesToReturn
- *AVERAGE_CHARS_PER_LINE);
- intlineTotal=0;
- try{
- randomAccessFile=newRandomAccessFile(file,"r");
- longbyteTotal=randomAccessFile.length();
- longbyteEstimateToRead=linesToReturn*AVERAGE_CHARS_PER_LINE
- *BYTES_PER_CHAR;
- longoffset=byteTotal-byteEstimateToRead;
- if(offset<0){
- offset=0;
- }
- randomAccessFile.seek(offset);
- //log.debug("SKIPIS::"+offset);
- Stringline=null;
- StringlineUTF8=null;
- while((line=randomAccessFile.readLine())!=null){
- lineUTF8=newString(line.getBytes("ISO8859_1"),"UTF-8");
- lineTotal++;
- buffer.append(lineUTF8).append("\n");
- }
- }finally{
- if(randomAccessFile!=null){
- try{
- randomAccessFile.close();
- }catch(IOExceptionex){
- }
- }
- }
- String[]resultLines=newString[linesToReturn];
- BufferedReaderin=null;
- try{
- in=newBufferedReader(newStringReader(buffer.toString()));
- intstart=lineTotal/*+2*/-linesToReturn;//Ex:55-10=45
- //~offset
- if(start<0)
- start=0;//notstartline
- for(inti=0;i<start;i++){
- in.readLine();//loopuntiltheoffset.Ex:loop0,1~~2
- //lines
- }
- inti=0;
- Stringline=null;
- while((line=in.readLine())!=null){
- resultLines[i]=line;
- i++;
- }
- }catch(IOExceptionie){
- log.error("Error"+ie);
- throwie;
- }finally{
- if(in!=null){
- try{
- in.close();
- }catch(IOExceptionex){
- }
- }
- }
- returnresultLines;
- }
- /**
- *单个文件拷贝。
- *
- *@paramsrcFilename
- *@paramdestFilename
- *@paramoverwrite
- *@throwsIOException
- */
- publicstaticvoidcopyFile(StringsrcFilename,StringdestFilename,
- booleanoverwrite)throwsIOException{
- FilesrcFile=newFile(srcFilename);
- //首先判断源文件是否存在
- if(!srcFile.exists()){
- thrownewFileNotFoundException("Cannotfindthesourcefile:"
- +srcFile.getAbsolutePath());
- }
- //判断源文件是否可读
- if(!srcFile.canRead()){
- thrownewIOException("Cannotreadthesourcefile:"
- +srcFile.getAbsolutePath());
- }
- FiledestFile=newFile(destFilename);
- if(overwrite==false){
- //目标文件存在就不覆盖
- if(destFile.exists())
- return;
- }else{
- //如果要覆盖已经存在的目标文件,首先判断是否目标文件可写。
- if(destFile.exists()){
- if(!destFile.canWrite()){
- thrownewIOException("Cannotwritethedestinationfile:"
- +destFile.getAbsolutePath());
- }
- }else{
- //不存在就创建一个新的空文件。
- if(!destFile.createNewFile()){
- thrownewIOException("Cannotwritethedestinationfile:"
- +destFile.getAbsolutePath());
- }
- }
- }
- BufferedInputStreaminputStream=null;
- BufferedOutputStreamoutputStream=null;
- byte[]block=newbyte[1024];
- try{
- inputStream=newBufferedInputStream(newFileInputStream(srcFile));
- outputStream=newBufferedOutputStream(newFileOutputStream(
- destFile));
- while(true){
- intreadLength=inputStream.read(block);
- if(readLength==-1)
- break;//endoffile
- outputStream.write(block,0,readLength);
- }
- }finally{
- if(inputStream!=null){
- try{
- inputStream.close();
- }catch(IOExceptionex){
- //justignore
- }
- }
- if(outputStream!=null){
- try{
- outputStream.close();
- }catch(IOExceptionex){
- //justignore
- }
- }
- }
- }
- /**
- *单个文件拷贝。
- *
- *@paramsrcFile
- *@paramdestFile
- *@paramoverwrite
- *是否覆盖目的文件
- *@throwsIOException
- */
- publicstaticvoidcopyFile(FilesrcFile,FiledestFile,booleanoverwrite)
- throwsIOException{
- //首先判断源文件是否存在
- if(!srcFile.exists()){
- thrownewFileNotFoundException("Cannotfindthesourcefile:"
- +srcFile.getAbsolutePath());
- }
- //判断源文件是否可读
- if(!srcFile.canRead()){
- thrownewIOException("Cannotreadthesourcefile:"
- +srcFile.getAbsolutePath());
- }
- if(overwrite==false){
- //目标文件存在就不覆盖
- if(destFile.exists())
- return;
- }else{
- //如果要覆盖已经存在的目标文件,首先判断是否目标文件可写。
- if(destFile.exists()){
- if(!destFile.canWrite()){
- thrownewIOException("Cannotwritethedestinationfile:"
- +destFile.getAbsolutePath());
- }
- }else{
- //不存在就创建一个新的空文件。
- if(!destFile.createNewFile()){
- thrownewIOException("Cannotwritethedestinationfile:"
- +destFile.getAbsolutePath());
- }
- }
- }
- BufferedInputStreaminputStream=null;
- BufferedOutputStreamoutputStream=null;
- byte[]block=newbyte[1024];
- try{
- inputStream=newBufferedInputStream(newFileInputStream(srcFile));
- outputStream=newBufferedOutputStream(newFileOutputStream(
- destFile));
- while(true){
- intreadLength=inputStream.read(block);
- if(readLength==-1)
- break;//endoffile
- outputStream.write(block,0,readLength);
- }
- }finally{
- if(inputStream!=null){
- try{
- inputStream.close();
- }catch(IOExceptionex){
- //justignore
- }
- }
- if(outputStream!=null){
- try{
- outputStream.close();
- }catch(IOExceptionex){
- //justignore
- }
- }
- }
- }
- /**
- *拷贝文件,从源文件夹拷贝文件到目的文件夹。<br>
- *参数源文件夹和目的文件夹,最后都不要带文件路径符号,例如:c:/aa正确,c:/aa/错误。
- *
- *@paramsrcDirName
- *源文件夹名称,例如:c:/test/aa或者c:\\test\\aa
- *@paramdestDirName
- *目的文件夹名称,例如:c:/test/aa或者c:\\test\\aa
- *@paramoverwrite
- *是否覆盖目的文件夹下面的文件。
- *@throwsIOException
- */
- publicstaticvoidcopyFiles(StringsrcDirName,StringdestDirName,
- booleanoverwrite)throwsIOException{
- FilesrcDir=newFile(srcDirName);//声明源文件夹
- //首先判断源文件夹是否存在
- if(!srcDir.exists()){
- thrownewFileNotFoundException(
- "Cannotfindthesourcedirectory:"
- +srcDir.getAbsolutePath());
- }
- FiledestDir=newFile(destDirName);
- if(overwrite==false){
- if(destDir.exists()){
- //donothing
- }else{
- if(destDir.mkdirs()==false){
- thrownewIOException(
- "Cannotcreatethedestinationdirectories="
- +destDir);
- }
- }
- }else{
- //覆盖存在的目的文件夹
- if(destDir.exists()){
- //donothing
- }else{
- //createanewdirectory
- if(destDir.mkdirs()==false){
- thrownewIOException(
- "Cannotcreatethedestinationdirectories="
- +destDir);
- }
- }
- }
- //循环查找源文件夹目录下面的文件(屏蔽子文件夹),然后将其拷贝到指定的目的文件夹下面。
- File[]srcFiles=srcDir.listFiles();
- if(srcFiles==null||srcFiles.length<1){
- //thrownewIOException("Cannotfindanyfilefromsource
- //directory!!!");
- return;//donothing
- }
- //开始复制文件
- intSRCLEN=srcFiles.length;
- for(inti=0;i<SRCLEN;i++){
- //FiletempSrcFile=srcFiles[i];
- FiledestFile=newFile(destDirName+File.separator
- +srcFiles[i].getName());
- //注意构造文件对象时候,文件名字符串中不能包含文件路径分隔符";".
- //log.debug(destFile);
- if(srcFiles[i].isFile()){
- copyFile(srcFiles[i],destFile,overwrite);
- }else{
- //在这里进行递归调用,就可以实现子文件夹的拷贝
- copyFiles(srcFiles[i].getAbsolutePath(),destDirName
- +File.separator+srcFiles[i].getName(),overwrite);
- }
- }
- }
- /**
- *压缩文件。注意:中文文件名称和中文的评论会乱码。
- *@paramsrcFilename
- *@paramdestFilename
- *@paramoverwrite
- *@throwsIOException
- */
- publicstaticvoidzipFile(StringsrcFilename,StringdestFilename,
- booleanoverwrite)throwsIOException{
- FilesrcFile=newFile(srcFilename);
- //首先判断源文件是否存在
- if(!srcFile.exists()){
- thrownewFileNotFoundException("Cannotfindthesourcefile:"
- +srcFile.getAbsolutePath());
- }
- //判断源文件是否可读
- if(!srcFile.canRead()){
- thrownewIOException("Cannotreadthesourcefile:"
- +srcFile.getAbsolutePath());
- }
- if(destFilename==null||destFilename.trim().equals("")){
- destFilename=srcFilename+".zip";
- }else{
- destFilename+=".zip";
- }
- FiledestFile=newFile(destFilename);
- if(overwrite==false){
- //目标文件存在就不覆盖
- if(destFile.exists())
- return;
- }else{
- //如果要覆盖已经存在的目标文件,首先判断是否目标文件可写。
- if(destFile.exists()){
- if(!destFile.canWrite()){
- thrownewIOException("Cannotwritethedestinationfile:"
- +destFile.getAbsolutePath());
- }
- }else{
- //不存在就创建一个新的空文件。
- if(!destFile.createNewFile()){
- thrownewIOException("Cannotwritethedestinationfile:"
- +destFile.getAbsolutePath());
- }
- }
- }
- BufferedInputStreaminputStream=null;
- BufferedOutputStreamoutputStream=null;
- ZipOutputStreamzipOutputStream=null;
- byte[]block=newbyte[1024];
- try{
- inputStream=newBufferedInputStream(newFileInputStream(srcFile));
- outputStream=newBufferedOutputStream(newFileOutputStream(destFile));
- zipOutputStream=newZipOutputStream(outputStream);
- zipOutputStream.setComment("通过java程序压缩的");
- ZipEntryzipEntry=newZipEntry(srcFile.getName());
- zipEntry.setComment("zipEntry通过java程序压缩的");
- zipOutputStream.putNextEntry(zipEntry);
- while(true){
- intreadLength=inputStream.read(block);
- if(readLength==-1)
- break;//endoffile
- zipOutputStream.write(block,0,readLength);
- }
- zipOutputStream.flush();
- zipOutputStream.finish();
- }finally{
- if(inputStream!=null){
- try{
- inputStream.close();
- }catch(IOExceptionex){
- //justignore
- }
- }
- if(outputStream!=null){