我在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)));
}
现在,当他运行此过程时,他同时期望file_1和file_2。但是,当只有file_1时,我也想让它通过。我该如何指定?
答案 0 :(得分:4)
您可以使用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])));
}
}
允许使用任意数量的文件名调用您的方法:
loadFiles("a.txt");
loadFiles("a.txt", "b.txt");
...
当有一个简单的替代方案时,不需要不必要的方法重载。
答案 1 :(得分:2)
Java不支持参数的默认值或跳过参数。 这正是重载进入图片的地方
定义另一种方法
public void loadFiles(String file_1) throws FileNotFoundException, IOException {
...
}
答案 2 :(得分:0)
如Eran所述,“......”(Spread运算符接受'n'个参数)。这有点类似于数组参数列表(例如,main(String args []))。在Java 8中引入了扩展运算符(...)。但是,为了更好地理解一个简单的示例,演示'...'扩展运算符如下所示
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");
}
}