要合并目录中所有文件的内容,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 的类包含 main 函数。将创建一个新文件类型及其位置 需要创建新文件的位置作为参数传递给它。
创建一个 PrintWriter 实例,并将目录中存在的文件名存储在字符串中 array。文件名被迭代,并使用BufferedReader实例进行读取。无论读取到什么内容,都会保留 写入新文件并存储。写入器也被冲洗,因此不会留下任何残留物。
以上是Java程序合并目录中所有文件的内容的详细内容。更多信息请关注PHP中文网其他相关文章!