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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With