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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

jitaiLin   2021-03-30 我要评论

复制文件的三种方法:

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();
 }
}

总结

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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们