我正在寻找一种方法将代码块传递给方法,然后该方法将对传递给方法的其他参数执行操作,获取这些操作的结果,并将这些结果传递给传递给方法的代码块。为清楚起见:
private static void method1(String filename, int sheetNum) {
runOnSheet(filename, () -> {
doStuffWithStream(FileInputStream fileStream); // Does something with a file stream
doOtherStuffWithStream(FileInputStream fileStream); // Does something else with a file stream
});
}
// Elsewhere
private static void runOnFile(String fileName, Runnable block1) {
try {
fileStream = new FileInputStream(fileName);
} catch (IOException e) {
e.printStackTrace();
}
block1.run(); // I'd like to pass fileStream to this code block. Ideally i could do block1.run(fileStream );
fileStream.close();
}
我希望能够在任何需要打开文件的地方重用runOnFile,在流上运行一些代码并关闭流。
我真正想要做的是更复杂,除了FileInputStream之外还使用其他库,但我希望实现的结构是相同的。
感谢您的帮助!
答案 0 :(得分:6)
Java 8+有一个名为private static void method1(String filename, int sheetNum) {
runOnFile(filename, (fileStream) -> {
doStuffWithStream(fileStream);
doOtherStuffWithStream(fileStream);
});
}
// Elsewhere
private static void runOnFile(String fileName, Consumer<FileInputStream> block1) {
try {
fileStream = new FileInputStream(fileName);
} catch (IOException e) {
e.printStackTrace();
}
block1.accept(fileStrean);
fileStream.close();
}
的类,可用于您的用例:
customize
try-with-resource
编辑:正如Dimitri使用// Elsewhere
private static void runOnFile(String fileName, Consumer<FileInputStream> block1) {
try (FileInputStream fis = new FileInputStream(fileName)) {
block1.accept(fis);
} catch (IOException e) {
e.printStackTrace();
}
}
语法所建议的那样:
assetlinks.json
答案 1 :(得分:2)
尝试这样的事情:
private static void method1(String filename, int sheetNum)
{
try ( final FileInputStream fileStream = new FileInputStream(filename))
{
runOnSheet(filename, () ->
{
doStuffWithStream(fileStream); // Does something with a file stream
doOtherStuffWithStream(fileStream); // Does something else with a file stream
});
}
}