在Java中复制文件可以使用以下方法:
使用Java IO库中的FileInputStream和FileOutputStream类进行复制操作。示例代码如下:import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class FileCopy { public static void main(String[] args) { File sourceFile = new File("source.txt"); File destFile = new File("dest.txt"); try (FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destFile)) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } System.out.println("File copied successfully!"); } catch (IOException e) { e.printStackTrace(); } }}使用Apache Commons IO库中的FileUtils类进行复制操作。示例代码如下:import org.apache.commons.io.FileUtils;import java.io.File;import java.io.IOException;public class FileCopy { public static void main(String[] args) { File sourceFile = new File("source.txt"); File destFile = new File("dest.txt"); try { FileUtils.copyFile(sourceFile, destFile); System.out.println("File copied successfully!"); } catch (IOException e) { e.printStackTrace(); } }}这两种方法都是常用的文件复制方法,你可以根据自己的需求选择适合的方法来实现文件复制操作。




