Search code examples
javaloopsinputargs

Read input files from args just by declaring their sum and a delay for processing


This is a tricky one for me since I haven't tried it again.

So I am trying to import a specific number of input text files to my program and specify a delay.
Let me explain:

java -jar program.jar 5 10  

This is just an example since the numbers can vary.
In this example I want to read 5 input files and then pass each one to a method after 10 seconds.

Every input file will be named: input[1...n].txt
input1.txt is passed into a method which does some stuff and then after 10sec input2.txt should enter.

I have no idea how to do this. I understand that I have to look for args[0] files in the directory of the file, but how do I look for input1.txt?

public static void main(String[] args) {
        int fileNumber = args[0];
        int delay = args[1]
        Q2fix ks = new Q2fix(args[0]);
        ks.fill();

}

Solution

  • You may use a loop to check for each numbered file:

    public static void main(String[] args) {
        int fileNumber = Integer.parseInt(args[0]);
        int delay = Integer.parseInt(args[1]);
    
        for (int i=1; i <= fileNumber; ++i) {
            String filename = "/some/path/to/input" + i + ".txt";
            Q2fix ks = new Q2fix(filename);
            ks.fill();
            Thread.sleep(delay);
        }
    }
    

    I am assuming here that your delay is already in milliseconds. If it be in seconds, then you would want to divide by 1000 before calling Thread#sleep. And Thread#sleep tells the current thread to sleep for some amount of time.