JAVA中关于文件的移动和复制

package com.day21.test;

import java.io.*;

/**
 * 将文件移动或者复制到其他地方
 */
public class Test2 {
    public static void main(String[] args) {
        File start = new File("E:\\111.txt");
        File end = new File("E:\\1\\01 linux");
        File end2 = new File("E:\\1\\01 linux\\1.txt");
        //move(start,end);
        //copy(start,end2);
        copy1(start,end2);
    }

    /**
     * 复制文件
     * @param in    起始目录
     * @param out   终止目录
     */
    public static void copy(File in,File out)  {
        try {
            FileInputStream fis = new FileInputStream(in);
            FileOutputStream fos = new FileOutputStream(out);
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) !=-1){
                fos.write(bytes,0,len);
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 复制文件(缓冲)
     * @param in    起始目录
     * @param out   终止目录
     */
    public static void copy1(File in,File out){
        try {
            FileInputStream fis = new FileInputStream(in);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);
            FileOutputStream fos = new FileOutputStream(out);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fos);
            int len = 0;
            while ((len = bufferedInputStream.read()) != -1){
                bufferedOutputStream.write(len);
            }
            bufferedInputStream.close();
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将一个文件移动到文件夹中
     * @param in    起始目录
     * @param out   终止目录
     */
    public static void move(File in,File out){
        // 如果目的文件夹不存在就创建文件夹
        if(!out.exists()){
            out.mkdir();
        }
        // 目的文件路径 = 目的目录路径 + 源文件路径
        File file = new File(out + File.separator + in.getName());
        if(in.renameTo(file)){
            System.out.println("sucess");
        }else{
            System.out.println("false");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值