前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java 把文件从一个目录复制到另一个目录

java 把文件从一个目录复制到另一个目录

作者头像
崔笑颜
发布2020-06-08 16:08:06
1.7K0
发布2020-06-08 16:08:06
举报

方法一:简单粗暴,直接使用copy(),如果目标存在,先使用delete()删除,再复制;

方法二:使用输入输出流。(代码注释部分)

代码语言:javascript
复制
package eg2;
 
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Scanner;
 
/******************
 * 文件的复制
 *******************/
 
public class Test2_3 {
 
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入指定文件夹路径:");
        String oldpath = sc.next();
        System.out.println("请输入目标文件夹路径:");
        String newpath = sc.next();
        System.out.println("请输入要复制的文件名:");
        String filename = sc.next();
        copy(filename, oldpath, newpath);
        System.out.println("复制完成!");
    }
 
    private static void copy(String filename, String oldpath, String newpath) throws IOException {
        // TODO Auto-generated method stub
        File oldpaths = new File(oldpath + "/" + filename);
        File newpaths = new File(newpath + "/" + filename);
        if (!newpaths.exists()) {
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        } else {
            newpaths.delete();
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        }
 
        // String newfile = "";
        // newfile += newpaths;
        // FileInputStream in = new FileInputStream(oldpaths);
        // File file = new File(newfile);
        // if (!file.exists()) {
        // file.createNewFile();
        // }
        // FileOutputStream out = new FileOutputStream(newpaths);
        // byte[] buffer = new byte[1024];
        // int c;
        // while ((c = in.read(buffer)) != -1) {
        // for (int i = 0; i < c; i++) {
        // out.write(buffer[i]);
        // }
        // }
        // in.close();
        // out.close();
    }
 
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档