diff --git a/hutool-core/src/main/java/cn/hutool/core/stream/StreamUtil.java b/hutool-core/src/main/java/cn/hutool/core/stream/StreamUtil.java index 52ebd85b1..69e426bd0 100644 --- a/hutool-core/src/main/java/cn/hutool/core/stream/StreamUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/stream/StreamUtil.java @@ -1,7 +1,15 @@ package cn.hutool.core.stream; import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.io.IORuntimeException; +import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.CharsetUtil; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Spliterators; import java.util.function.Function; import java.util.function.UnaryOperator; @@ -17,11 +25,9 @@ import java.util.stream.StreamSupport; public class StreamUtil { @SafeVarargs - public static Stream of(T... values) { - if (null == values) { - return null; - } - return Stream.of(values); + public static Stream of(T... array) { + Assert.notNull(array, "Array must be not null!"); + return Stream.of(array); } /** @@ -44,14 +50,58 @@ public class StreamUtil { * @return {@link Stream} */ public static Stream of(Iterable iterable, boolean parallel) { - if (null == iterable) { - return null; - } + Assert.notNull(iterable, "Iterable must be not null!"); return StreamSupport.stream( Spliterators.spliterator(CollUtil.toCollection(iterable), 0), parallel); } + /** + * 按行读取文件为{@link Stream} + * + * @param file 路径 + * @return {@link Stream} + */ + public static Stream of(File file) { + return of(file, CharsetUtil.CHARSET_UTF_8); + } + + /** + * 按行读取文件为{@link Stream} + * + * @param path 路径 + * @return {@link Stream} + */ + public static Stream of(Path path) { + return of(path, CharsetUtil.CHARSET_UTF_8); + } + + /** + * 按行读取文件为{@link Stream} + * + * @param charset 编码 + * @return {@link Stream} + */ + public static Stream of(File file, Charset charset) { + Assert.notNull(file, "File must be not null!"); + return of(file.toPath(), charset); + } + + /** + * 按行读取文件为{@link Stream} + * + * @param path 路径 + * @param charset 编码 + * @return {@link Stream} + */ + public static Stream of(Path path, Charset charset) { + try { + return Files.lines(path, charset); + } catch (IOException e) { + throw new IORuntimeException(e); + } + } + /** * 通过函数创建Stream * @@ -68,9 +118,9 @@ public class StreamUtil { /** * 将Stream中所有元素以指定分隔符,合并为一个字符串,对象默认调用toString方法 * - * @param stream {@link Stream} - * @param delimiter 分隔符 - * @param 元素类型 + * @param stream {@link Stream} + * @param delimiter 分隔符 + * @param 元素类型 * @return 字符串 */ public static String join(Stream stream, CharSequence delimiter) {