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 Demo001 {
public static void writeFile(String strSrc, String dest) {
FileWriter writer = null;
FileReader reader = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
File file = new File(dest);
if (!file.exists()) {
file.createNewFile();
}
// 这里的true,是以追加的方式写
writer = new FileWriter(dest, true);
reader = new FileReader(strSrc);
String str = null;
br = new BufferedReader(reader);
bw = new BufferedWriter(writer);
while ((str = br.readLine()) != null) {
StringBuffer sb = new StringBuffer("");
sb.append(str + "\n");
bw.write(sb.toString());
}
br.close();
reader.close();
bw.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Demo001.writeFile("D:/1.txt", "D:/3.txt");
Demo001.writeFile("D:/2.txt", "D:/3.txt");
}
}
本人实现了下读取read.txt写入到write.txt末尾
import java.io.*;
public class WriteToFileEnd {
/**
* 读取read.txt写入到write.txt末尾
*/
public static void main(String[] args) {
// 字节输入流
FileInputStream fis = null;
RandomAccessFile randomFile = null;
try {
// 打开一个随机访问文件流,按读写方式
randomFile = new RandomAccessFile("d:\\write.txt", "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
randomFile.seek(fileLength);
File fileRead = new File("d:\\read.txt");
// 定义一个字节数组 相当于缓存 一点一点读进来 一下都进来 内存放不下
byte[] bytes = new byte[1024];
fis = new FileInputStream(fileRead);
int n = 0;// 得到实际读取到的字节数
// 循环读取
while ((n = fis.read(bytes)) != -1) {// 读完了
// 把字节转成string
String str = new String(bytes, 0, n);
randomFile.writeBytes(str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
randomFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}