我需要从文件中读取并写入字符串数组。我对 forEach 语句有点困惑。如何写入字符串数组,每行 1?
package input;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ReadFile {
public String[] currentBookData;
public static void getBookData() throws IOException {
try (Stream<String> stream = Files.lines(Paths.get("C:/test.txt"), Charset.defaultCharset())) {
stream.forEach(System.out::println);
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
最佳答案
您可以使用其中之一
stream.toArray();
或
String [] s = new String[0];
stream.collect(Collectors.toList()).toArray(s);
关于java - 如何使用 forEach 语句写入字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495600/