2017-06-29 77 views
1

我正在尋找一種方法將代碼塊傳遞給一個方法,該方法將對傳遞給方法的其他參數執行操作,獲取這些操作的結果並將這些結果傳遞給代碼塊傳遞給方法。爲了清晰:傳遞方法的lambda參數

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以外還使用其他庫,但是我希望完成的結構是一樣的。

感謝您的幫助!

回答

4

的Java 8+有一個名爲Consumer類可用於您的用例: https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html

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(); 
} 

編輯:

// Elsewhere 
private static void runOnFile(String fileName, Consumer<FileInputStream> block1) { 
    try (FileInputStream fis = new FileInputStream(fileName)) { 
     block1.accept(fis); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+4

爲了更加清楚,我會在'runOnFile'方法中加入'try-with-resources' – Dimitri

+0

我接受這個答案是正確的,我將使用try-with-resource。謝謝您的幫助! –

1

試着這麼做:由於迪米特里使用try-with-resource語法建議這個:

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 
    }); 
    } 
} 
+0

儘管對於這個例子來說,它的工作原理是,我希望能夠從其他方法調用runOnFile,它會產生相同的效果。但是,謝謝你展示了試用資源。 –