2017-06-14 67 views
8

對於我的特定任務,我需要將FileChannel中的數據讀取爲StringStream(或Collection)。從FileChannel讀取所有行至字符串流

在常規NIOPath我們可以使用一個方便的方法Files.lines(...)它返回一個Stream<String>。我需要一個相同的結果,但是從FileChannel而不是Path

public static Stream<String> lines(final FileChannel channel) { 
//... 
} 

任何想法如何做到這一點?

回答

8

我假設你希望在返回Stream關閉要關閉的通道,因此最簡單的方法是

public static Stream<String> lines(FileChannel channel) { 
    BufferedReader br = new BufferedReader(Channels.newReader(channel, "UTF-8")); 
    return br.lines().onClose(() -> { 
     try { br.close(); } 
     catch (IOException ex) { throw new UncheckedIOException(ex); } 
    }); 
} 

實際上它並不需要一個FileChannel作爲輸入,ReadableByteChannel就足夠了。

請注意,這也屬於「常規NIO」; java.nio.file有時是referred to as 「NIO.2」

+2

哦,你已經通過'onClose'糾正了我們代碼庫中的一個錯誤。謝謝 – Eugene