zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java文件操作工具类分享(file文件工具类)

JAVA文件工具 操作 分享 File
2023-06-13 09:15:17 时间

复制代码代码如下:


importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.text.DateFormat;
importjava.text.MessageFormat;
importjava.util.ArrayList;
importjava.util.Date;
importjava.util.Enumeration;
importjava.util.List;
importjava.util.Locale;
importjava.util.StringTokenizer;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipFile;

/**
 *
 *@authorIBM
 *
 */

publicclassFileUtil{

 publicstaticStringdirSplit="\\";//linuxwindows
 /**
 *savefileaccrodingtophysicaldirectoryinfomation
 *
 *@paramphysicalDir
 *           physicaldirectory
 *@paramfname
 *           filenameofdestination
 *@paramistream
 *           inputstreamofdestinationfile
 *@return
 */

 publicstaticbooleanSaveFileByPhysicalDir(StringphysicalPath,
   InputStreamistream){

  booleanflag=false;
  try{
   OutputStreamos=newFileOutputStream(physicalPath);
   intreadBytes=0;
   bytebuffer[]=newbyte[8192];
   while((readBytes=istream.read(buffer,0,8192))!=-1){
    os.write(buffer,0,readBytes);
   }
   os.close();
   flag=true;
  }catch(FileNotFoundExceptione){

   e.printStackTrace();
  }catch(IOExceptione){

   e.printStackTrace();
  }
  returnflag;
 }

 publicstaticbooleanCreateDirectory(Stringdir){
  Filef=newFile(dir);
  if(!f.exists()){
   f.mkdirs();
  }
  returntrue;
 }

 
 publicstaticvoidsaveAsFileOutputStream(StringphysicalPath,Stringcontent){
   Filefile=newFile(physicalPath);
   booleanb=file.getParentFile().isDirectory();
   if(!b){
    Filetem=newFile(file.getParent());
    //tem.getParentFile().setWritable(true);
    tem.mkdirs();//创建目录
   }
   //Log.info(file.getParent()+";"+file.getParentFile().isDirectory());
   FileOutputStreamfoutput=null;
   try{
    foutput=newFileOutputStream(physicalPath);

    foutput.write(content.getBytes("UTF-8"));
    //foutput.write(content.getBytes());
   }catch(IOExceptionex){
    ex.printStackTrace();
    thrownewRuntimeException(ex);
   }finally{
    try{
     foutput.flush();
     foutput.close();
    }catch(IOExceptionex){
     ex.printStackTrace();
     thrownewRuntimeException(ex);
    }
   }
    //Log.info("文件保存成功:"+physicalPath);
  }



 /**
    *COPY文件
    *@paramsrcFileString
    *@paramdesFileString
    *@returnboolean
    */
   publicbooleancopyToFile(StringsrcFile,StringdesFile){
       Filescrfile=newFile(srcFile);
       if(scrfile.isFile()==true){
           intlength;
           FileInputStreamfis=null;
           try{
               fis=newFileInputStream(scrfile);
           }
           catch(FileNotFoundExceptionex){
               ex.printStackTrace();
           }
           Filedesfile=newFile(desFile);

           FileOutputStreamfos=null;
           try{
               fos=newFileOutputStream(desfile,false);
           }
           catch(FileNotFoundExceptionex){
               ex.printStackTrace();
           }
           desfile=null;
           length=(int)scrfile.length();
           byte[]b=newbyte[length];
           try{
               fis.read(b);
               fis.close();
               fos.write(b);
               fos.close();
           }
           catch(IOExceptione){
               e.printStackTrace();
           }
       }else{
           scrfile=null;
           returnfalse;
       }
       scrfile=null;
       returntrue;
   }

   /**
    *COPY文件夹
    *@paramsourceDirString
    *@paramdestDirString
    *@returnboolean
    */
   publicbooleancopyDir(StringsourceDir,StringdestDir){
       FilesourceFile=newFile(sourceDir);
       StringtempSource;
       StringtempDest;
       StringfileName;
       File[]files=sourceFile.listFiles();
       for(inti=0;i<files.length;i++){
           fileName=files[i].getName();
           tempSource=sourceDir+"/"+fileName;
           tempDest=destDir+"/"+fileName;
           if(files[i].isFile()){
               copyToFile(tempSource,tempDest);
           }else{
               copyDir(tempSource,tempDest);
           }
       }
       sourceFile=null;
       returntrue;
   }

   /**
    *删除指定目录及其中的所有内容。
    *@paramdir要删除的目录
    *@return删除成功时返回true,否则返回false。
    */
   publicbooleandeleteDirectory(Filedir){
       File[]entries=dir.listFiles();
       intsz=entries.length;
       for(inti=0;i<sz;i++){
           if(entries[i].isDirectory()){
               if(!deleteDirectory(entries[i])){
                   returnfalse;
               }
           }else{
               if(!entries[i].delete()){
                   returnfalse;
               }
           }
       }
       if(!dir.delete()){
           returnfalse;
       }
       returntrue;
   }

   

   /**
    *Fileexistcheck
    *
    *@paramsFileNameFileName
    *@returnbooleantrue-exist<br>
    *                false-notexist
    */
   publicstaticbooleancheckExist(StringsFileName){

    booleanresult=false;

      try{
      Filef=newFile(sFileName);

      //if(f.exists()&&f.isFile()&&f.canRead()){
   if(f.exists()&&f.isFile()){
     result=true;
   }else{
     result=false;
   }
   }catch(Exceptione){
        result=false;
   }

       /*return*/
       returnresult;
   }

   /**
    *GetFileSize
    *
    *@paramsFileNameFileName
    *@returnlongFile"ssize(byte)whenFilenotexistreturn-1
    */
   publicstaticlonggetSize(StringsFileName){

       longlSize=0;

       try{
     Filef=newFile(sFileName);

             //exist
     if(f.exists()){
      if(f.isFile()&&f.canRead()){
       lSize=f.length();
      }else{
       lSize=-1;
      }
             //notexist
     }else{
         lSize=0;
     }
   }catch(Exceptione){
        lSize=-1;
   }
   /*return*/
   returnlSize;
   }

 /**
 *FileDelete
 *
 *@paramsFileNameFileNmae
 *@returnbooleantrue-DeleteSuccess<br>
 *                false-DeleteFail
 */
   publicstaticbooleandeleteFromName(StringsFileName){

       booleanbReturn=true;

       try{
           FileoFile=newFile(sFileName);

          //exist
          if(oFile.exists()){
           //DeleteFile
           booleanbResult=oFile.delete();
           //DeleteFail
           if(bResult==false){
               bReturn=false;
           }

           //notexist
          }else{

          }

  }catch(Exceptione){
   bReturn=false;
  }

  //return
  returnbReturn;
   }

 /**
 *FileUnzip
 *
 *@paramsToPath UnzipDirectorypath
 *@paramsZipFileUnzipFileName
 */
 @SuppressWarnings("rawtypes")
publicstaticvoidreleaseZip(StringsToPath,StringsZipFile)throwsException{

 if(null==sToPath||("").equals(sToPath.trim())){
   FileobjZipFile=newFile(sZipFile);
   sToPath=objZipFile.getParent();
 }
 ZipFilezfile=newZipFile(sZipFile);
 EnumerationzList=zfile.entries();
 ZipEntryze=null;
 byte[]buf=newbyte[1024];
 while(zList.hasMoreElements()){

   ze=(ZipEntry)zList.nextElement();
   if(ze.isDirectory()){
    continue;
   }

   OutputStreamos=
   newBufferedOutputStream(
   newFileOutputStream(getRealFileName(sToPath,ze.getName())));
   InputStreamis=newBufferedInputStream(zfile.getInputStream(ze));
   intreadLen=0;
   while((readLen=is.read(buf,0,1024))!=-1){
    os.write(buf,0,readLen);
   }
   is.close();
   os.close();
 }
 zfile.close();
 }

 /**
 *getRealFileName
 *
 *@param baseDir  RootDirectory
 *@param absFileName absoluteDirectoryFileName
 *@returnjava.io.File    Returnfile
 */
 @SuppressWarnings({"rawtypes","unchecked"})
privatestaticFilegetRealFileName(StringbaseDir,StringabsFileName)throwsException{

 Fileret=null;

 Listdirs=newArrayList();
 StringTokenizerst=newStringTokenizer(absFileName,System.getProperty("file.separator"));
 while(st.hasMoreTokens()){
  dirs.add(st.nextToken());
 }

 ret=newFile(baseDir);
 if(dirs.size()>1){
  for(inti=0;i<dirs.size()-1;i++){
   ret=newFile(ret,(String)dirs.get(i));
  }
 }
 if(!ret.exists()){
  ret.mkdirs();
 }
 ret=newFile(ret,(String)dirs.get(dirs.size()-1));
 returnret;
 }

 /**
 *copyFile
 *
 *@param srcFile  SourceFile
 *@param targetFile  Targetfile
 */
 @SuppressWarnings("resource")
 staticpublicvoidcopyFile(StringsrcFile,StringtargetFile)throwsIOException
 {

  FileInputStreamreader=newFileInputStream(srcFile);
  FileOutputStreamwriter=newFileOutputStream(targetFile);

  byte[]buffer=newbyte[4096];
  intlen;

  try
  {
   reader=newFileInputStream(srcFile);
   writer=newFileOutputStream(targetFile);

   while((len=reader.read(buffer))>0)
   {
    writer.write(buffer,0,len);
   }
  }
  catch(IOExceptione)
  {
   throwe;
  }
  finally
  {
   if(writer!=null)writer.close();
   if(reader!=null)reader.close();
  }
 }

 /**
 *renameFile
 *
 *@param srcFile  SourceFile
 *@param targetFile  Targetfile
 */
 staticpublicvoidrenameFile(StringsrcFile,StringtargetFile)throwsIOException
 {
  try{
   copyFile(srcFile,targetFile);
   deleteFromName(srcFile);
  }catch(IOExceptione){
   throwe;
  }
 }


 publicstaticvoidwrite(StringtivoliMsg,StringlogFileName){
 try{
   byte[] bMsg=tivoliMsg.getBytes();
   FileOutputStreamfOut=newFileOutputStream(logFileName,true);
   fOut.write(bMsg);
   fOut.close();
 }catch(IOExceptione){
  //throwtheexception     
 }

 }
 /**
 *Thismethodisusedtologthemessageswithtimestamp,errorcodeandthemethoddetails
 *@paramerrorCdString
 *@paramclassNameString
 *@parammethodNameString
 *@parammsgString
 */
 publicstaticvoidwriteLog(StringlogFile,StringbatchId,StringexceptionInfo){

 DateFormatdf=DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.DEFAULT,Locale.JAPANESE);

 Objectargs[]={df.format(newDate()),batchId,exceptionInfo};

 StringfmtMsg=MessageFormat.format("{0}:{1}:{2}",args);

 try{

  Filelogfile=newFile(logFile);
  if(!logfile.exists()){
   logfile.createNewFile();
  }

     FileWriterfw=newFileWriter(logFile,true);
     fw.write(fmtMsg);
     fw.write(System.getProperty("line.separator"));

     fw.flush();
     fw.close();

 }catch(Exceptione){
 }
 }

 publicstaticStringreadTextFile(StringrealPath)throwsException{
 Filefile=newFile(realPath);
  if(!file.exists()){
   System.out.println("Filenotexist!");
   returnnull;
  }
  BufferedReaderbr=newBufferedReader(newInputStreamReader(newFileInputStream(realPath),"UTF-8"));  
  Stringtemp="";
  Stringtxt="";
  while((temp=br.readLine())!=null){
   txt+=temp;
   }  
  br.close();
 returntxt;
 }
}