0

I've got this java program which is currently programmed to take in a filename as an argument from command line, open it and then read it. I want to configure it so I can pass it a directory name and the program will execute on the files in the directory. Not really sure how to go about it. This is my code currently:

static XMLInputFactory factory = XMLInputFactory.newInstance(); 
XMLEventReader reader = null;  
XMLEventFactory eventFactory = null;

public XMLTrimmer(File ifp) throws XMLStreamException, FileNotFoundException {
    this(new FileInputStream(ifp));
}

public XMLTrimmer(InputStream str) throws XMLStreamException, FileNotFoundException {
    try {
        reader = factory.createXMLEventReader(str);
    } catch (XMLStreamException e) {
        e.printStackTrace();
    }
}

In main it goes like this:

public static void main(String args[]) throws IOException, XMLStreamException {

    File readFile = new File(args[0]);

    XMLTrimmer xr = new XMLTrimmer(readFile);

please let me know, any help is appreciated.

Ben Zifkin
  • 892
  • 2
  • 8
  • 16
  • I'd suggest checking the documentation for File. – Hot Licks Aug 27 '14 at 21:08
  • Are you wanting your java code to do this or are you OK to have a script run your java code for each file in the directory? – user3885927 Aug 27 '14 at 21:13
  • Only two options: Change the program to take multiple arguments and/or check if an arg is really a directory (J4v4's answer) or write a script or batch file that calls the program once for each file – Gus Aug 27 '14 at 21:15

2 Answers2

3

You will have to modify the code to check if the argument points to a directory:

if(readFile.isDirectory()) {
    for(File file : readFile.listFiles()) {
        //process all files in the directory
    }
} else {
    //process single file
}

You can also add support for more than one argument (since args is an array of Strings) or no argument.

J4v4
  • 780
  • 4
  • 9
0

If you want to go through all files recursively you might rather need

public static void main(String[] args) {
    File readFile = new File(args[0]);

    executeForPath(readFile);
}

private static void executeForPath(File readFile) {
    if (readFile.isDirectory()) {
        for (File file : readFile.listFiles()) {
            executeForPath(file);
        }
    } else {
        XMLTrimmer xr = new XMLTrimmer(readFile);
    }
}
damienix
  • 6,463
  • 1
  • 23
  • 30