Java文件复制与读写

函数介绍

    public String readLine():每次读取文件的一行,当文件读取完毕时,返回null
    public int read(byte[] b):将文件内容读取到字节数组b
    public int write(byte[] b, int off, int len):将字节数组中[off, off+len)位置的内容写入文件

文件复制

    其实文件复制,在读取一个文件的同时,将读取到的内容写入另外一个文件中

代码实例

package cn.edu.pzhu;

import java.io.*;

public class FileCopyDemo {

    public static void main(String[] args) throws IOException {
        String src = "D:\\Test\\in.data";
        String des = "D:\\Test\\out.data";
        //复制文件
        boolean success = copyFile(src, des);
        if (success) {
            //文件复制成功
            System.out.println("读取成功,该文件的内容是:");
            readFile(des);
        } else {
            //复制失败
            System.out.println("Copy failed");
        }
    }

    //读取文件
    public static void readFile(String des) throws IOException {
        File file = new File(des);
        BufferedReader buffRead = new BufferedReader(new FileReader(file));
        String line = null;
        while((line = buffRead.readLine()) != null) {
            System.out.println(line);
        }
    }

    //创建文件
    public static void createFile(String fileName) throws IOException {
        File file = new File(fileName);
        if (!file.exists()) {
            file.createNewFile(); //创建该文件
        }
    }

    //将文件从src复制到des
    public static boolean copyFile(String src, String des) throws IOException {
        boolean ok = true;
        File fsrc = new File(src);
        File fdes = new File(des);
        if (!fsrc.exists()) {
            System.out.println(fsrc.getAbsolutePath() + "is not exists!");
            return false;
        }
        //目标文件不存在
        if (!fdes.exists()) {
            createFile(des);
        }
        //目标文件是文件夹
        if (fdes.isDirectory()) {
            System.out.println(fdes.getAbsolutePath()+" is a directory!");
            return false;
        }
        //开始复制文件
        //创建文件输入流
        FileInputStream fin = null;
        FileOutputStream fout = null;
        try {
            fin = new FileInputStream(fsrc);
            //创建文件输出流
            fout = new FileOutputStream(fdes);
            //创建缓存区
            byte buff[] = new byte[1024];
            int len;
            while((len = fin.read(buff)) != -1) {
                fout.write(buff, 0, len);
            }
        } catch (Exception e) {
            ok = false;
            e.printStackTrace();
        } finally {
            fin.close();
            fout.close();
        }
        return ok;
    }

}

如有不当之处欢迎指出!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值