Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java process multiple string arguments

Tags:

java

I have the following code in java:

public void loadFiles(String file_1, String file_2) throws FileNotFoundException, IOException {

    String line_file1;
    String line_file2;
    BufferedReader buf_file1 = new BufferedReader(new FileReader(new File(file_1)));
    BufferedReader buf_file2 = new BufferedReader(new FileReader(new File(file_2)));

}

Now when he runs this process, he expects both a file_1 and file_2. But I also want to make it go through when there is only a file_1. How should I specify this?

like image 905
user1987607 Avatar asked Dec 15 '25 15:12

user1987607


1 Answers

You can use varargs :

public void loadFiles(String... fileNames) throws FileNotFoundException, IOException {
    BufferedReader[] buf_file = new BufferedReader[fileNames.length];
    for (int i = 0; i < fileNames.length; i++) {
        buf_file[i] = new BufferedReader(new FileReader(new File(fileNames[i])));
    }
}

Which allows your method to be called with any number of file names :

loadFiles("a.txt");
loadFiles("a.txt", "b.txt");
...

No need for unnecessary method overloading when there's a simple alternative.

like image 51
Eran Avatar answered Dec 17 '25 04:12

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!