- 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){
文件操作FileUtil.java
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.