复制文件的三种方法

来源:互联网 发布:淘宝散片cpu可靠吗 编辑:程序博客网 时间:2024/06/03 18:30

复制文件的三种方法:

1、Files.copy(path, new FileOutputStream(dest));。

2、利用字节流。

3、利用字符流。

代码实现如下:


package com.tiger.io;import java.io.*;import java.nio.file.*;/** * 复制文件的三种方式 * @author tiger * @Date 2017年7月24日--上午8:52:54 */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();}}






原创粉丝点击