2016-05-06 25 views
0

我有一行文本文件。我想使用Java 8 Stream來讀取它,並將讀取的行分配給String變量。如何使用Java 8將讀取行分配給字符串變量流

我在這裏

public String getParamFromFile() { 
    String param = ""; 
    try (Stream<String> stream = Files.lines(Paths.get("./resources/price.txt"))) { 
     param = stream.forEach(); //how to assign the read line to this field? 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return param; 
} 
+0

只需使用Files.readAllLines並獲取返回的List的第一個元素。 –

+0

@SotiriosDelimanolis:它說,'資源類型列表沒有實現java.lang.AutoCloseable' \t \t嘗試(名單流= Files.readAllLines(Paths.get( 「./資源/ price.txt」)) ){ \t \t \t \t \t} –

+0

您不需要從您當前的代碼片段中使用「try-with-resources」。你會想'readAllLines'調用一個簡單的'try-catch',因爲它聲明'IOException'是一個潛在的拋出異常。 –

回答

2

卡住你應該能夠做先手流的第一個元素,

Files.lines(Paths.get("./resources/price.txt"))).findFirst().get() 

findFirst方法返回一個Optional<String>類型,而不是null如果沒有第一條線。如果文件中沒有第一行,您可以指定默認值,

Files.lines(Paths.get("./resources/price.txt"))).findFirst().orElse("default string") 
相關問題