【发布时间】:2017-03-16 16:25:39
【问题描述】:
我对 lambda 表达式有疑问。我的代码:
public static void main(String[] args) {
Function<String, String> lambda = path -> {
String result = null;
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
result = result + line;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
};
}
我现在正在尝试编写这样的代码:
public static void main(String[] args) throws IOException {
Function<String, String> lambda = path -> {
String result = null;
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
result = result + line;
}
return result;
};
}
这可能吗?我只能使用 java.util.function。我尝试从“lambda”中删除 try catch,而我的“main”方法应该正在捕获该异常。
【问题讨论】:
-
请注意,在您的第一个解决方案中,您永远不会关闭
BufferedRead,从而导致内存泄漏。
标签: java lambda exception-handling