Java可以通过使用FileInputStream和FileOutputStream来实现文件复制功能。例如,以下是一种实现文件复制的方法:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileCopy { public static void main(String[] args) { String sourcePath = "path_to_source_file"; String destinationPath = "path_to_destination_file"; try { FileInputStream fis = new FileInputStream(sourcePath); FileOutputStream fos = new FileOutputStream(destinationPath); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } fis.close(); fos.close(); System.out.println("文件复制成功!"); } catch (IOException e) { e.printStackTrace(); } } }
在上面的代码中,你需要将 path_to_source_file
替换为源文件的路径,将 path_to_destination_file
替换为目标文件的路径。程序会逐个读取源文件中的字节,并将其写入目标文件。最后,程序会关闭输入流和输出流,并打印出 “文件复制成功!” 的消息。