3

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?

1
  • public void loadFiles(String... files) Commented Jun 23, 2016 at 8:06

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Mhm, I don't understand. I should then nowhere specify 'file_1' and 'file_2'? I will make an edit to the original post, to clarify the situation better
@user1987607 Instead of file_1 and file_2, you have fileNames[0], fileName[1], etc... (which you can iterate over in a loop, as shown in my answer).
2

Java doesn't support default values to arguments or skipping the arguments . This is exactly where overloading comes into picture

define another method

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

...

}

Comments

0

As said by Eran, "..." (Spread operator accepts 'n' arguments). This is kind of similar to list of array arguments (E.g., main(String args[])). Spread operator(...) has been introduced in Java 8. However, for your better understanding a simple example demonstrating the '...' spread operator as below

public class TestClass {

public static void test(String... args){
    for(String str: args){
        System.out.println(str);
    }
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
    test("a","m","a", "r");
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.