文本文件复制:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TextCopy {
public static void main(String[] args) {
String srcPath = "source.txt";
String destPath = "target.txt";
try {
File sourceFile = new File(srcPath);
if (!sourceFile.exists()) {
sourceFile.createNewFile(); // 自动创建文件
FileWriter fw = new FileWriter(sourceFile);
fw.write("这是自动创建的源文件内容\n");
fw.write("文件复制测试成功!\n");
fw.close();
System.out.println("已自动创建 source.txt");
}
} catch (IOException e) {
System.out.println("创建文件失败");
e.printStackTrace();
}
try (
BufferedReader br = new BufferedReader(new FileReader(srcPath));
BufferedWriter bw = new BufferedWriter(new FileWriter(destPath))
) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
System.out.println("文本文件复制完成!");
} catch (IOException e) {
System.out.println("运行失败!");
e.printStackTrace();
}
}
}
任意文件复制:
import java.io.*;
public class AnyFileCopy {
public static void main(String[] args) {
String srcPath = "test.txt"; // 自动创建的测试文件
String destPath = "copy_test.txt"; // 复制后的文件
try {
File sourceFile = new File(srcPath);
if (!sourceFile.exists()) {
sourceFile.createNewFile();
FileWriter fw = new FileWriter(sourceFile);
fw.write("我是自动创建的测试内容\n");
fw.write("文件复制成功!");
fw.close();
System.out.println("已自动创建源文件:" + srcPath);
}
try (
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath))
) {
byte[] buffer = new byte[8192];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
System.out.println("文件复制完成!");
System.out.println("源文件:" + srcPath);
System.out.println("目标文件:" + destPath);
}
} catch (IOException e) {
System.out.println("复制失败");
e.printStackTrace();
}
}
}