Java文件复制与读写

时间:2021-04-11 20:53:27

函数介绍

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

}

如有不当之处欢迎指出!