合并的结果应该是这样的:
现在是这样的
public static void main(String[] args) { List<Object> list = new ArrayList<>(); File file1 = new File("d:\ti.txt"); File file2 = new File("d:\titi.txt"); list.add(file1); list.add(file2); FileWriter writer = null; BufferedReader reader = null; try { for (int i = 0; i < list.size(); i++) { File f = (File) list.get(i); writer = new FileWriter("d:\concatenation.txt"); reader = new BufferedReader(new FileReader(f)); String l; while ((l = reader.readLine()) != null) { writer.write(l); } } writer.flush(); writer.close(); reader.close(); } catch (IOException e) { e.printStackTrace(); } }
运行,得到结果如下
怎么只有第二个文件的内容?
原来这一句writer = new FileWriter("d:\concatenation.txt");写在循环里了,因为writer是引用,所以writer是先指向了一个new FileWriter("d:\concatenation.txt")地址,循环一下,又指向了一个新的new FileWriter("d:\concatenation.txt")地址,这时文件只有文件二了,所以写入的只有文件二的内容了
总的目标是一个,所以要写在循环外
public static void main(String[] args) { List<Object> list = new ArrayList<>(); File file1 = new File("d:\ti.txt"); File file2 = new File("d:\titi.txt"); list.add(file1); list.add(file2); FileWriter writer = null; BufferedReader reader = null; try { writer = new FileWriter("d:\concatenation.txt"); for (int i = 0; i < list.size(); i++) { File f = (File) list.get(i); reader = new BufferedReader(new FileReader(f)); String l; while ((l = reader.readLine()) != null) { writer.write(l); } } writer.flush(); writer.close(); reader.close(); } catch (IOException e) { e.printStackTrace(); } }