最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用jdk7的nio2操作文件拷貝和剪切示例

 更新時(shí)間:2014年01月29日 09:14:40   作者:  
使用jdk7的NIO2進(jìn)行文件或文件夾的拷貝移動(dòng)操作??梢宰詣?dòng)創(chuàng)建路徑,差異化更新文件,簡單的出錯(cuò)重連機(jī)制

復(fù)制代碼 代碼如下:

package com.xyq.io.simply.core;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

import com.xyq.io.enums.FileTypeMode;
import com.xyq.io.enums.OptionFile_TYPE;
import com.xyq.io.inf.NewNIoInf;
import com.xyq.io.util.FindFileUtil;
import com.xyq.io.util.MD5Util;

public class NewNIO implements NewNIoInf {

 /***
  * 拷貝或者移動(dòng)文件
  */
 @Override
 public boolean copeOrMoveFile(String src, String tar, OptionFile_TYPE type) {

  return realCopeOrMoveFile(Paths.get(src), tar, type);
 }

 private boolean realCopeOrMoveFile(Path srcPath, String tar,
   OptionFile_TYPE type) {

  Path tarPath = null;
  boolean copeSuccess = true;
  // 必須原始文件存在
  if (srcPath.toFile().exists()) {
   /***
    * 如果原始路徑是帶斜杠的那么就認(rèn)為這是一個(gè)文件夾
    */
   if (isDir(tar))
    tarPath = Paths.get(tar + File.separator
      + srcPath.toFile().getName());
   else
    tarPath = Paths.get(tar);
   /***
    * 然后進(jìn)行N次(可以作為參數(shù))拷貝操作(出錯(cuò)重連),是否覆蓋拷貝,拷貝屬性,拷貝操作不能使用回滾選項(xiàng)
    */
   for (int i = 0; i < 3; i++) {
    /***
     * 如果是目標(biāo)文件已經(jīng)存在
     */
    if (tarPath.toFile().exists()) {
     /***
      * 如果驗(yàn)證兩個(gè)文件夾是相同的,拷貝選項(xiàng)下就不用拷貝,移動(dòng)選項(xiàng)下就是刪除原始文件
      */
     // 拷貝
     if (OptionFile_TYPE.COPE.equals(type)) {
      if (equalsFile(srcPath.toFile(), tarPath.toFile()))
       return true;
      else
       copeSuccess = copeFile(srcPath, tarPath, true);
     }
     /***
      * 移動(dòng)操作,這里得非常小心,正常情況下,如果兩個(gè)文件是一樣的話,
      * 那么直接刪除原始文件就可以了。但是,如果兩個(gè)文件的一樣,并且地址也
      * 是一樣的話,那么就不能刪除原始的了,因?yàn)榫褪峭粋€(gè)文件,不能刪除的。
      */
     else if (OptionFile_TYPE.MOVE.equals(type)) {
      if (equalsFile(srcPath.toFile(), tarPath.toFile())) {
       if (!srcPath.toFile().getAbsoluteFile()
         .equals(tarPath.toFile().getAbsoluteFile()))
        try {
         Files.delete(srcPath);
         /***
          * 之所以要手動(dòng)指向true,是因?yàn)榭赡艽嬖谇懊鎰h除失敗的情況
          */
         if (!copeSuccess)
          copeSuccess = true;
        } catch (IOException e) {
         copeSuccess = false;
        }
       // 前面因?yàn)橛挟惓5目赡芫筒恢苯觬eturn,這里就可以了
       else
        return true;
      } else
       copeSuccess = moveFile(srcPath, tarPath);
     }
    }
    /***
     * 當(dāng)目標(biāo)文件不存在的時(shí)候,先判斷父類文件夾是可創(chuàng) 建(父類文件夾存在或者可以創(chuàng)建),可創(chuàng)建時(shí)就創(chuàng)建
     */
    else {
     File par = tarPath.getParent().toFile();
     /***
      * 如果父類文件夾不存在并且無法創(chuàng)建,那么就不用拷貝了
      */
     if (!par.exists() && !par.mkdirs())
      copeSuccess = false;
     else if (OptionFile_TYPE.COPE.equals(type))
      copeSuccess = copeFile(srcPath, tarPath, false);
     else if (OptionFile_TYPE.MOVE.equals(type))
      copeSuccess = moveFile(srcPath, tarPath);
    }
    // 如果操作成功,跳出循環(huán)
    if (copeSuccess)
     break;
   }
  } else
   copeSuccess = false;
  return copeSuccess;
 }

 /****
  * 拷貝文件
  */

 private boolean copeFile(Path srcPath, Path tarPath, boolean isExist) {

  if (isExist)
   try {
    Files.copy(srcPath, tarPath,
      StandardCopyOption.REPLACE_EXISTING,
      StandardCopyOption.COPY_ATTRIBUTES);
   } catch (IOException e) {
    return false;
   }
  else
   try {
    Files.copy(srcPath, tarPath, StandardCopyOption.COPY_ATTRIBUTES);
   } catch (IOException e) {
    return false;
   }
  return true;
 }

 /***
  * 移動(dòng)文件,不能使用屬性選項(xiàng)
  *
  * @param srcPath
  * @param tarPath
  * @return
  */
 private boolean moveFile(Path srcPath, Path tarPath) {

  try {
   Files.move(srcPath, tarPath, StandardCopyOption.ATOMIC_MOVE);
  } catch (IOException e) {
   return false;
  }
  return true;
 }

 /***
  * 判斷path路徑是否是一個(gè)文件夾
  *
  * @param path
  * @return
  */
 private boolean isDir(String path) {

  char lastC = path.charAt(path.length() - 1);
  if (lastC == '\\' || lastC == '/')
   return true;
  return false;
 }

 /***
  * 這是來驗(yàn)證兩個(gè)文件是否相同,只是簡單驗(yàn)證,可以強(qiáng)制必須使用md5進(jìn)行驗(yàn)證
  */

 public boolean equalsFile(File src, File tar) {

  // 如果兩個(gè)文件的長度不一樣,那么肯定兩個(gè)文件是不一樣的
  if (src.length() != tar.length())
   return false;
  if (!src.getName().equals(tar.getName())
    || src.lastModified() != tar.lastModified())
   return MD5Util.EncoderFileByMd5(src).equals(
     MD5Util.EncoderFileByMd5(tar));
  return true;
 }

 /***
  * 拷貝或者移動(dòng)文件夾
  */
 @Override
 public void copeOrMoveDirectory(String src, final String tar, int tierSize,
   final OptionFile_TYPE type) {

  if (!new File(src).exists())
   throw new RuntimeException("找不到原始文件夾" + src);
  final int rootPos = getRootPosition(new File(src), tierSize);
  if (rootPos != -1) {
   try {
    Files.walkFileTree(Paths.get(src), new FileVisitor<Path>() {

     String tarDirString = null;

     /***
      * 到達(dá)文件夾前,先把目標(biāo)路徑寫好
      *
      * @param dir
      * @param attrs
      * @return
      * @throws IOException
      */
     @Override
     public FileVisitResult preVisitDirectory(Path dir,
       BasicFileAttributes attrs) throws IOException {

      tarDirString = dir.toFile().getAbsolutePath();
      tarDirString = tar + tarDirString.substring(rootPos)
        + File.separator;
      return FileVisitResult.CONTINUE;
     }

     /***
      * 到達(dá)文件之后,進(jìn)行拷貝或者移動(dòng)操作
      *
      * @param file
      * @param attrs
      * @return
      * @throws IOException
      */
     @Override
     public FileVisitResult visitFile(Path file,
       BasicFileAttributes attrs) throws IOException {

      File f = file.toFile();
      if (f.exists() && f.canRead() && !f.isHidden())
       realCopeOrMoveFile(file, tarDirString, type);
      return FileVisitResult.CONTINUE;
     }

     @Override
     public FileVisitResult visitFileFailed(Path file,
       IOException exc) throws IOException {

      return FileVisitResult.CONTINUE;
     }

     /***
      * 到達(dá)文件夾后
      *
      * @param dir
      * @param exc
      * @return
      * @throws IOException
      */
     @Override
     public FileVisitResult postVisitDirectory(Path dir,
       IOException exc) throws IOException {
      return FileVisitResult.CONTINUE;
     }
    });
   } catch (Exception e) {
    e.printStackTrace();
   }
   // 如果是剪切操作,并且剪切成功,那么就要?jiǎng)h除所有文件夾
   if (OptionFile_TYPE.MOVE.equals(type) && isBlockDir(src))
    delDir(src);
  } else
   throw new RuntimeException("指定父類文件夾層次錯(cuò)誤~~~");
 }

 /***
  * 根據(jù)指定層次獲取指定盤符的位置
  */

 private int getRootPosition(File file, int tier) {

  if (file != null) {
   String path = file.getAbsolutePath();
   int cc = 0;
   for (int i = path.length() - 1; i >= 0; i--) {
    if (path.charAt(i) == '\\') {
     cc++;
     if (cc == tier + 1) {
      cc = i;
      return cc;
     }
    }
   }
  }
  return -1;
 }

 /***
  * 查看該文件夾下是否還有文件
  *
  * @param dirPath
  * @return
  */
 private boolean isBlockDir(String dirPath) {

  File dir = new File(dirPath);
  File[] dirList = dir.listFiles();
  if (dirList == null || dirList.length == 0)
   return true;
  else {
   // 尋找文件
   for (File f : dirList)
    if (!f.isDirectory())
     return false;
  }
  return true;
 }

 /***
  * 刪除空文件夾
  *
  * @param dirPath
  */
 private void delDir(String dirPath) {

  File dir = new File(dirPath);
  File[] dirList = dir.listFiles();
  if (dirList == null || dirList.length == 0)
   dir.delete();
  else {
   // 刪除所有文件
   for (File f : dirList)
    if (f.isDirectory())
     delDir(f.getAbsolutePath());
    else
     f.delete();
   // 刪除完當(dāng)前文件夾下所有文件后刪除文件夾
   dirList = dir.listFiles();
   if (dirList.length == 0)
    dir.delete();
  }
 }

 /***
  * 根據(jù)文件類型查找相關(guān)的文件
  */
 @Override
 public List<String> findFilesByType(String dir, String[] keys,
   boolean isMatchCase) throws IOException {

  List<String> list = new ArrayList<String>();
  Files.walkFileTree(Paths.get(dir), new FindFileUtil(keys, isMatchCase,
    list, FileTypeMode.TYPES));
  return list;
 }

 /***
  * 根據(jù)文件名稱查找相關(guān)的文件
  */
 @Override
 public List<String> findFilesByName(String dir, String[] keys,
   boolean isMatchCase) throws IOException {

  List<String> list = new ArrayList<String>();
  Files.walkFileTree(Paths.get(dir), new FindFileUtil(keys, isMatchCase,
    list, FileTypeMode.NAMES));
  return list;
 }

 public static void main(String[] args) throws IOException {

  NewNIoInf inf = new NewNIO();
  inf.copeOrMoveFile("e:/cc/dd/11.txt", "e:/XX/xxx/zzz/",
    OptionFile_TYPE.COPE);
  inf.copeOrMoveDirectory("e:\\BB\\CC\\DD", "e:\\",1, OptionFile_TYPE.MOVE);
  System.out.println(inf.findFilesByName("D:\\workspace", new String[] { "txt" },
    false).size());

 }

}
---------------------------
package com.xyq.io.enums;

/***
 * 文件類型
 * @author xyq
 *
 */
public enum FileTypeMode {

 TYPES,NAMES
}

---------------------------------
package com.xyq.io.enums;

/***
 * 操作文件的類型
 * @author xyq
 *
 */
public enum OptionFile_TYPE {

 COPE,MOVE;
}
---------------------
package com.xyq.io.inf;

import java.io.IOException;
import java.util.List;

import com.xyq.io.enums.OptionFile_TYPE;

public interface NewNIoInf {

 /***
  * 拷貝或者移動(dòng)文件
  * @param src
  * @param tar
  * @return
  */
 public boolean copeOrMoveFile(String src,String tar,OptionFile_TYPE type);

 /***
  * 拷貝或者移動(dòng)文件夾
  * @param src
  * @param tar
  * @param tierSize 層次,拷貝完成后的路徑0只是當(dāng)前文件夾,+1就是加一級父類文件夾(但不拷貝父類內(nèi)容)
  * @param type
  */
 public void copeOrMoveDirectory(String src,String tar,int tierSize,OptionFile_TYPE type);

 /**
  * 根據(jù)文件類型查找相關(guān)文件集合,多種類型時(shí)用逗號(hào)隔開
  *
  * @param dir
  *            目錄
  * @param keys
  *            文件類型
  * @param isMatchCase
  *            是否區(qū)分大小寫
  * @return
  * @throws IOException
  */
 List<String> findFilesByType(String dir, String[] keys, boolean isMatchCase)
   throws IOException;

 /**
  * 根據(jù)文件名稱查找相關(guān)文件集合,多種民稱時(shí)用逗號(hào)隔開
  *
  * @param dir
  *            目錄
  * @param keys
  *            文件名稱
  * @param isMatchCase
  *            是否區(qū)分大小寫
  * @return
  * @throws IOException
  */
 List<String> findFilesByName(String dir, String[] keys, boolean isMatchCase)
   throws IOException;
}
--------------------
package com.xyq.io.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;

import com.xyq.io.enums.FileTypeMode;

public class FindFileUtil extends SimpleFileVisitor<Path> {

 /***
  * 關(guān)鍵詞列表,是否轉(zhuǎn)換大小寫,返回結(jié)果集
  */
 private String[] keyArray = null;
 private boolean isMatchCase;
 private List<String> resultList;
 private FileTypeMode mode;

 public FindFileUtil(String[] keyArray, boolean isMatchCase,
   List<String> resultList, FileTypeMode mode) {

  this.keyArray = keyArray;
  this.isMatchCase = isMatchCase;
  this.resultList = resultList;
  this.mode = mode;
 }

 @SuppressWarnings("unused")
 private FindFileUtil() {
 }

 @Override
 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
   throws IOException {

  File f = file.toFile();
  if (f.exists() && f.canRead() && !f.isHidden())
  if (this.keyArray != null) {
   for (String key : this.keyArray) {
    if (!this.isMatchCase)
     key = key.toLowerCase();
    if (matchFile(file, this.mode, key, isMatchCase))
     resultList.add(file.toString());
   }
  }
  return FileVisitResult.CONTINUE;
 }

 /***
  * 根據(jù)大小寫和類型或名稱進(jìn)行文件匹配
  *
  * @param file
  * @param mode
  * @param key
  * @param isMatchCase
  * @return
  */
 private boolean matchFile(Path file, FileTypeMode mode, String key,
   boolean isMatchCase) {

  File f = file.toFile();
  if (f.exists() && f.canRead() && !f.isHidden()
    && !"System Volume Information".equals(f.getName())) {
   String fileName = null;
   if (FileTypeMode.TYPES.equals(mode)) {

    fileName = file.toString();
    return isMatchCase ? fileName.endsWith(key) : fileName
      .toLowerCase().endsWith(key);
   } else if (FileTypeMode.NAMES.equals(mode)) {
    fileName = file.toFile().getName();
    return isMatchCase ? (fileName.indexOf(key) == -1 ? false
      : true)
      : (fileName.toLowerCase().indexOf(key) == -1 ? false
        : true);
   }
  }
  return false;
 }

 @Override
 public FileVisitResult visitFileFailed(Path file, IOException exc)
   throws IOException {
  //如果錯(cuò)誤信息中包含X:\System Volume Information,這是表示系統(tǒng)的隱藏盤,是不能讀的
  System.out.println(exc.getMessage());
  return FileVisitResult.CONTINUE;
 }
}
--------------------------
package com.xyq.io.util;

import java.io.Closeable;

public class CloseIoUtil {

 /***
  * 關(guān)閉IO流
  *
  * @param cls
  */
 public static void closeAll(Closeable... cls) {

  if (cls != null) {
   for (Closeable cl : cls) {
    try {
     if (cl != null)
      cl.close();
    } catch (Exception e) {

    } finally {
     cl = null;
    }
   }
  }
 }
}
-----------------------------
package com.xyq.io.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

public class MD5Util {
 /***
  * 加密字符串
  *
  * @param str
  * @return
  * @throws NoSuchAlgorithmException
  * @throws UnsupportedEncodingException
  */
 public static String EncoderStringByMd5(String str)
   throws NoSuchAlgorithmException, UnsupportedEncodingException {

  // 確定計(jì)算方法
  MessageDigest md5 = MessageDigest.getInstance("MD5");
  BASE64Encoder base64en = new BASE64Encoder();

  // 加密后的字符串
  String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
  return newstr;
 }

 /***
  * 加密文件
  *
  * @param file
  * @return
  * @throws NoSuchAlgorithmException
  * @throws IOException
  */
 public static String EncoderFileByMd5(File file) {

  String newstr = null;
  FileInputStream fis = null;
  BufferedInputStream bis = null;
  try {
   // 確定計(jì)算方法
   MessageDigest md5 = MessageDigest.getInstance("MD5");
   BASE64Encoder base64en = new BASE64Encoder();
   byte[] buffer = new byte[1024];
   fis = new FileInputStream(file);
   bis = new BufferedInputStream(fis);
   int length = -1;
   while ((length = bis.read(buffer)) != -1)
    md5.update(buffer, 0, length);
   // 加密后的字符串
   newstr = base64en.encode(md5.digest());
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   CloseIoUtil.closeAll(bis, fis);
  }
  return newstr;
 }
 public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {

  
  System.out.println(EncoderStringByMd5("23"));
 }
}

相關(guān)文章

  • java實(shí)現(xiàn)查找替換功能

    java實(shí)現(xiàn)查找替換功能

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)查找替換功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • 詳解Spring如何掃描自定義的注解

    詳解Spring如何掃描自定義的注解

    本文給大家詳細(xì)介紹了Spring如何掃描自定義的注解,在Spring中,可以使用注解來實(shí)現(xiàn)依賴注入、AOP等功能,同時(shí),Spring也支持自定義注解,使得開發(fā)人員可以更靈活地使用注解,需要的朋友可以參考下
    2024-02-02
  • JPA配置方式+逆向工程映射到Entity實(shí)體類

    JPA配置方式+逆向工程映射到Entity實(shí)體類

    這篇文章主要介紹了JPA配置方式+逆向工程映射到Entity實(shí)體類,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • HttpServletResponse亂碼問題_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    HttpServletResponse亂碼問題_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章主要介紹了HttpServletResponse亂碼問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-07-07
  • MyBatis配置與CRUD超詳細(xì)講解

    MyBatis配置與CRUD超詳細(xì)講解

    這篇文章主要介紹了MyBatis配置與CRUD,CRUD是指在做計(jì)算處理時(shí)的增加(Create)、讀取(Read)、更新(Update)和刪除(Delete)幾個(gè)單詞的首字母簡寫。CRUD主要被用在描述軟件系統(tǒng)中數(shù)據(jù)庫或者持久層的基本操作功能
    2023-02-02
  • VScode 打造完美java開發(fā)環(huán)境最新教程

    VScode 打造完美java開發(fā)環(huán)境最新教程

    這篇文章主要介紹了VScode 打造完美java開發(fā)環(huán)境最新教程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • 基于String不可變字符與StringBuilder可變字符的效率問題

    基于String不可變字符與StringBuilder可變字符的效率問題

    這篇文章主要介紹了String不可變字符與StringBuilder可變字符的效率問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • java學(xué)習(xí)筆記之馬踏棋盤算法

    java學(xué)習(xí)筆記之馬踏棋盤算法

    這篇文章主要為大家詳細(xì)介紹了java學(xué)習(xí)筆記之馬踏棋盤算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • Java annotation元注解原理實(shí)例解析

    Java annotation元注解原理實(shí)例解析

    這篇文章主要介紹了Java annotation元注解原理實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • Java線程并發(fā)工具類CountDownLatch原理及用法

    Java線程并發(fā)工具類CountDownLatch原理及用法

    這篇文章主要介紹了Java線程并發(fā)工具類CountDownLatch原理及用法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10

最新評論

密山市| 南部县| 万年县| 高雄县| 阜宁县| 清原| 成都市| 绵竹市| 平远县| 睢宁县| 丹阳市| 南郑县| 伊春市| 平舆县| 修文县| 额济纳旗| 视频| 五河县| 贡觉县| 琼中| 卓尼县| 衢州市| 凤翔县| 峨边| 独山县| 习水县| 思南县| 东方市| 桂阳县| 阳新县| 承德县| 柳河县| 叶城县| 萨嘎县| 祁东县| 南部县| 康平县| 巢湖市| 和田市| 蛟河市| 曲水县|