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

在Java中如何使用函数实现文件复制和移动操作

发布时间:2023-06-08 15:42:01

Java提供了许多实现文件复制和移动操作的函数,主要涉及到java.io包下的File类和InputStream/OutputSteam类。

一、文件复制

1. 使用缓冲字节数组进行复制

/**

 * 使用缓冲字节数组进行文件复制

 * @param sourcePath 源文件路径

 * @param targetPath 目标文件路径

 * @throws IOException

 */

public static void copyFile(String sourcePath, String targetPath) throws IOException {

    File sourceFile = new File(sourcePath);

    File targetFile = new File(targetPath);

    FileInputStream inputStream = new FileInputStream(sourceFile);

    FileOutputStream outputStream = new FileOutputStream(targetFile);

    byte[] buffer = new byte[1024];

    int len;

    while ((len = inputStream.read(buffer)) != -1) {

        outputStream.write(buffer, 0, len);

    }

    inputStream.close();

    outputStream.close();

}

2. 使用BufferedReader和BufferedWriter进行复制

/**

 * 使用BufferedReader和BufferedWriter进行文件复制

 * @param sourcePath 源文件路径

 * @param targetPath 目标文件路径

 * @throws IOException

 */

public static void copyFile(String sourcePath, String targetPath) throws IOException {

    File sourceFile = new File(sourcePath);

    File targetFile = new File(targetPath);

    BufferedReader reader = new BufferedReader(new FileReader(sourceFile));

    BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile));

    String line;

    while ((line = reader.readLine()) != null) {

        writer.write(line);

        writer.newLine();

    }

    reader.close();

    writer.close();

}

二、文件移动

文件移动实际上就是文件复制的一种特殊形式,只需要在复制完成后删除源文件即可。

/**

 * 使用缓冲字节数组进行文件移动

 * @param sourcePath 源文件路径

 * @param targetPath 目标文件路径

 * @throws IOException

 */

public static void moveFile(String sourcePath, String targetPath) throws IOException {

    copyFile(sourcePath, targetPath);

    File sourceFile = new File(sourcePath);

    sourceFile.delete();

}

三、总结

以上就是Java中使用函数实现文件复制和移动操作的方法。根据实际应用场景和文件大小选择适合的方法进行操作即可。除了上述方法外,也可以使用一些第三方库进行文件操作,如Apache Commons IO等。