ในการรวมเนื้อหาของไฟล์ทั้งหมดในไดเร็กทอรี รหัส 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 ยังถูกล้างเพื่อไม่ให้มีสารตกค้างเหลืออยู่