Search code examples
javaprintwriter

java copying input to multiple output files


I am trying to copy the contents of an inputFile to multiple other files. I am trying to do this using command line arguments.

However, I am having some difficulties with the closing of the printwriter. I don't know where or how i should do it. If i do it in my for-loop, the content only gets copied to one output file. I tried an if-statement but that didn't work either. If I close it outside of the for-loop. I get a 'cannot find symbol error' which makes sense since I declared it inside the for-loop.

My question thus is: How and where am I supposed to close the printwriter in this situation?

Thank you in advance.

import java.util.*;
import java.io.*;
public class try13 {
    public static void main(String[] args) throws FileNotFoundException {
        File inputFile = new File(args[0]);
        Scanner in = new Scanner(inputFile);
        for(int i = 1; i < args.length; i++) {
            PrintWriter out = new PrintWriter(args[i]);
            while (in.hasNextLine()) {
                String line = in.nextLine();
                out.println(line);
            }   
        }   
        in.close();
        out.close();
    }
}

Solution

  • First make an array of the PrintWriters, then copy each line read from the input to all of the outputs:

    import java.util.*;
    import java.io.*;
    public class try13 {
        public static void main(String[] args) throws FileNotFoundException {
            File inputFile = new File(args[0]);
            Scanner in = new Scanner(inputFile);
    
            /* Create all the writers and put then in a list */
            List<PrintWriter> writers = new ArrayList<>();
            for(int i = 1; i < args.length; i++) {
                writers.add(new PrintWriter(args[i]));
            }
    
            /* Read each line and write it to all writers */
            while (in.hasNextLine()) {
                String line = in.nextLine();
                writers.forEach(writer -> writer.println(line));
            }
    
            in.close();
    
            /* Close all the writers */
            writers.forEach(writer -> {
                    try {
                        writer.close();
                    } catch(Exception e) {}
            });
        }
    }
    

    If you are not using Java8, try this:

    /* Read each line and write it to all writers */
    while (in.hasNextLine()) {
        String line = in.nextLine();
        for(PrintWriter writer : writers) {
            writer.println(line);
        }
    }
    

    ... and this:

    /* Close all the writers */
    for(PrintWriter writer : writers) {
        try {
            writer.close();
        } catch(Exception e) {}
    }