文件移动

来源:互联网 发布:web前端优化面试题 编辑:程序博客网 时间:2024/05/18 02:25
  1.   /**  
  2.      * //1.从旧文件拷贝内容到新文件  
  3.      * //2.删除旧文件  
  4.      * @param oldPath the path+name of old file  
  5.      * @param newPath the path+name of new file  
  6.      * @throws Exception  
  7.      */  
  8. private void transferFile(String oldPath,String newPath) throws Exception {   
  9.            
  10.         int byteread = 0;   
  11.         File oldFile = new File(oldPath);   
  12.         FileInputStream fin = null;   
  13.         FileOutputStream fout = null;   
  14.         try{   
  15.             if(oldFile.exists()){   
  16.                 fin = new FileInputStream(oldFile);   
  17.                 fout = new FileOutputStream(newPath);   
  18.                 byte[] buffer = new byte[fin.available()]; 
  19.                 while( (byteread = fin.read(buffer)) != -1){   
  20.                     logger.debug("byteread=="+byteread);   
  21.                     fout.write(buffer,0,byteread);   
  22.                 }   
  23.                 if(fin != null){   
  24.                     fin.close();//如果流不关闭,则删除不了旧文件   
  25.                     this.delFile(oldFile);   
  26.                 }   
  27.             }else{   
  28.                 throw new Exception("需要转移的文件不存在!");   
  29.             }   
  30.         }catch(Exception e){   
  31.             e.printStackTrace();   
  32.             throw e;   
  33.         }finally{   
  34.             if(fin != null){   
  35.                 fin.close();   
  36.             }   
  37.         }   
  38.     }   
  39.   
  40.   
  41.     /**  
  42.      * 删除文件,只支持删除文件,不支持删除目录  
  43.      * @param file  
  44.      * @throws Exception  
  45.      */  
  46.     private void delFile(File file) throws Exception {   
  47.         if(!file.exists()) {   
  48.             throw new Exception("文件"+file.getName()+"不存在,请确认!");   
  49.         }   
  50.         if(file.isFile()){   
  51.             if(file.canWrite()){   
  52.                 file.delete();   
  53.             }else{   
  54.                 throw new Exception("文件"+file.getName()+"只读,无法删除,请手动删除!");   
  55.             }   
  56.         }else{   
  57.             throw new Exception("文件"+file.getName()+"不是一个标准的文件,有可能为目录,请确认!");   
  58.         }   
  59.     }   
原创粉丝点击