Java程序合并目录中所有文件的内容
要合并目录中所有文件的内容,Java代码如下-
示例
import java.io.*; public class Demo{ public static void main(String[] args) throws IOException{ File my_dir = new File("path to place where file is generated"); PrintWriter my_writer = new PrintWriter("The .txt where changes are stored"); String[] file_names = my_dir.list(); for (String file_names : fileNames){ System.out.println("Content read from " + file_names); File my_file = new File(my_dir, file_names); BufferedReader my_reader = new BufferedReader(new FileReader(my_file)); my_writer.println("The file contains " + file_names); String my_line = my_reader.readLine(); while (my_line != null){ my_writer.println(my_line); my_line = my_reader.readLine(); } my_writer.flush(); } System.out.println("All data from files have been read and " + my_dir.getName() + "merged"); } }
输出结果
All file contents will be merged into a single text file.
名为Demo的类包含主要功能。将创建一个新的文件类型,并将需要创建新文件的位置的位置作为参数传递给它。
创建一个PrintWriter实例,并将目录中存在的文件名存储在字符串数组中。文件名被迭代,并使用BufferedReader实例读取。读取的内容将写入新文件并存储。Writer也会被冲洗,因此不会残留任何残留物。