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;
}
只需使用Files.readAllLines并获取返回的List的第一个元素。 –
@SotiriosDelimanolis:它说,'资源类型列表没有实现java.lang.AutoCloseable' \t \t尝试(名单流= Files.readAllLines(Paths.get( “./资源/ price.txt”)) ){ \t \t \t \t \t} –
您不需要从您当前的代码片段中使用“try-with-resources”。你会想'readAllLines'调用一个简单的'try-catch',因为它声明'IOException'是一个潜在的抛出异常。 –