欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java复制文件常用的三种方法

程序员文章站 2024-02-28 08:59:34
复制文件的三种方法: 1、files.copy(path, new fileoutputstream(dest));。 2、利用字节流。 3、利用字符流。 代码实现...

复制文件的三种方法:

1、files.copy(path, new fileoutputstream(dest));。

2、利用字节流。

3、利用字符流。

代码实现如下:

package com.tiger.io;
import java.io.*;
import java.nio.file.*;
/**
 * 复制文件的三种方式
 * @author tiger
 * @date 
 */
public class copyfile {
 public static void main(string[] args) throws ioexception, ioexception {
 path path = paths.get("e:","17-06-15-am1.avi");
 string dest = "e:\\copy电影.avi";
 copy01(path, dest);
 string src = "e:\\[java典型应用彻查1000例:java入门].pdf";
 string dest1 = "e:\\copyfile.pdf";
 copy02(src, dest1);
 //copy03(src, dest1);
 }
 
 /**
 * 利用files工具copy
 * @param path
 * @param dest
 * @throws ioexception
 * @throws ioexception
 */
 public static void copy01(path path,string dest) throws ioexception, ioexception{
 //利用files工具类对文件进行复制,简化编程,只需要写一句。
 files.copy(path, new fileoutputstream(dest));
 }
 
 /**
 * 利用字节流复制
 * @param src
 * @param dest
 * @throws ioexception
 */
 public static void copy02(string src,string dest) throws ioexception{
 inputstream is = new bufferedinputstream(new fileinputstream(src));
 outputstream os = new bufferedoutputstream(new fileoutputstream(dest));
 //文件拷贝u,-- 循环+读取+写出
 byte[] b = new byte[10];//缓冲大小
 int len = 0;//接收长度
 //读取文件
 while (-1!=(len = is.read(b))) {
  //读入多少,写出多少,直到读完为止。
  os.write(b,0,len);
 }
 //强制刷出数据
 os.flush();
 //关闭流,先开后关
 os.close();
 is.close();
 }
 
 /**
 * 字符流复制
 * @param src
 * @param dest
 * @throws ioexception
 */
 public static void copy03(string src,string dest) throws ioexception{
 //字符输入流
 bufferedreader reader = new bufferedreader(new filereader(src));
 //字符输出流
 bufferedwriter writer = new bufferedwriter(new filewriter(dest));
 char[] cbuf = new char[24];
 int len = 0;
 //边读入边写出
 while ((len = reader.read(cbuf)) != -1) {
  writer.write(cbuf, 0, len);
 }
 //关闭流
 writer.close();
 reader.close();
 }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接