使用文件通道的方法进行文件复制

点击(此处)折叠或打开

  1. public void fileChannelCopy(File s, File t) {

  2.         FileInputStream fi = null;

  3.         FileOutputStream fo = null;

  4.         FileChannel in = null;

  5.         FileChannel out = null;

  6.         try {

  7.             fi = new FileInputStream(s);

  8.             fo = new FileOutputStream(t);

  9.             in = fi.getChannel();//得到对应的文件通道

  10.             out = fo.getChannel();//得到对应的文件通道

  11.             in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道

  12.         } catch (IOException e) {

  13.             e.printStackTrace();

  14.         } finally {

  15.             try {

  16.                 fi.close();

  17.                 in.close();

  18.                 fo.close();

  19.                 out.close();

  20.             } catch (IOException e) {

  21.                 e.printStackTrace();

  22.             }

  23.         }

  24.     }

以文件缓冲区的方式进行文件复制

点击(此处)折叠或打开

  1. private boolean copyFile (String fileFrom, String fileTo) {
  2.         try {
  3.             FileInputStream in = new java.io.FileInputStream(fileFrom);
  4.             FileOutputStream out = new FileOutputStream(fileTo);
  5.             byte[] bt = new byte[1024];
  6.             int count;
  7.             while ((count = in.read(bt)) > 0) {
  8.                 out.write(bt, 0, count);
  9.             }
  10.             in.close();
  11.             out.close();
  12.             return true;
  13.         } catch (IOException ex) {
  14.             return false;
  15.         }
  16.     }


09-28 06:29