欢迎访问宙启技术站
智能推送

Java中用于复制文件的函数

发布时间:2023-08-25 17:23:37

在Java中,可以使用java.io包下的File和InputStream,OutputStream类,以及Files类来复制文件。以下是一些常用的复制文件的函数:

1. 使用InputStream和OutputStream复制文件:

public static void copyFileUsingStreams(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

2. 使用Files类的copy()方法复制文件:

public static void copyFileUsingFiles(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

3. 使用BufferedReader和BufferedWriter复制文件:

public static void copyFileUsingBufferedReaderAndWriter(File source, File dest) throws IOException {
    BufferedReader reader = null;
    BufferedWriter writer = null;
    try {
        reader = new BufferedReader(new FileReader(source));
        writer = new BufferedWriter(new FileWriter(dest));
        char[] buffer = new char[1024];
        int length;
        while ((length = reader.read(buffer)) > 0) {
            writer.write(buffer, 0, length);
            writer.flush();
        }
    } finally {
        reader.close();
        writer.close();
    }
}

以上是几种常用的复制文件的函数,可以根据具体的需求选择合适的方法进行文件复制。