Java Fileoperations: copy the file name and content of 10 files in another

The copyFiles() method is a static method that throws an IOException. It first creates a new FileWriter object called output and opens the file “new_file.txt”. This object will be used to write the file names and contents to the new file.

Next, a loop is used to iterate over the 10 text files. Inside the loop, the file name is created using string concatenation: "file_" + i + ".txt". A new BufferedReader object is created to read the contents of the current file, and a String variable called content is initialized to an empty string.

A while loop is used to read the lines of the current file and append them to the content string. The readLine() method returns null when there are no more lines to read, which is the signal to exit the loop.

After the loop, the file name and content are written to the output object using the write() method. The file name and content are combined into a single string, separated by newline characters and extra whitespace for readability.

The copyFiles() method ends by closing the BufferedReader and FileWriter objects.

Finally, the main() method simply calls the copyFiles() method to execute the program.

Note that the try-catch block is not necessary in this example since the IOException is being thrown, but it could be included for error handling purposes in other cases.

import java.io.*;

public class Main {
    public static void copyFiles() throws IOException {
        FileWriter output = new FileWriter("new_file.txt");
        for (int i = 1; i <= 10; i++) {
            String fileName = "file_" + i + ".txt";
            BufferedReader input = new BufferedReader(new FileReader(fileName));
            String content = "";
            String line;
            while ((line = input.readLine()) != null) {
                content += line + "\n";
            }
            output.write("File name: " + fileName + "\nContent: " + content + "\n\n");
            input.close();
        }
        output.close();
    }

    public static void main(String[] args) throws IOException {
        copyFiles();
    }
}