PHP8 —— New String Helpers

新增了三个字符串函数,str_starts_with, str_ends_with, str_contains, PHP 的函数这么方便,很难想象竟然一直没有这几个。 str_starts_with 判断字符串是否以另一个字符串开头,在PHP7以及之前 $id = 'inv_abcdefgh'; $result = strpos($id, 'inv_') === 0; var_dump($result); // true PHP8 中可以直接这么写 $result = str_starts_with($id, 'inv_'); str_ends_with 判断字符串是否以另外一个字符串结尾,在 PHP7 及之前,比较麻烦,通常是这么写 $id = 'abcd_inv'; $result = strpos(strrev($id), strrev('_inv')) === 0; 或者 $result = substr($id, -1 * strlen('_inv')) === '_inv'; 或者上正则吧 $result = preg_match('/_inv$/', $id) === 1; 看起来都是比较麻烦的。PHP8 里面可以简化成下面这样了 $id = 'abcd_inv'; $result = str_ends_with($id, '_ind'); str_contains 字符串包含,PHP8 之前一般就是 strpos 来实现了 $url = 'https://example?for=bar'; $result = strpos($url, '?') !== FALSE; PHP8 就直接一点 $result = str_contains($url, '?');

Java 学习笔记 —— 获取文件Stream

java.nio.file.Files类中的静态列表方法将Path用作参数,并返回包装DirectoryStream的Stream。 DirectoryStream接口扩展了AutoCloseable,因此使用list方法最好通过try-with-resources构造完成。

try (Stream<Path> list = Files.list(Paths.get("src/main/java"))) { 
    list.forEach(System.out::println);
} catch (IOException e) { 
    e.printStackTrace();
}

假设这是在具有标准Maven或Gradle结构的项目的根目录中执行的,这将打印 src/main/java 目录中所有文件和文件夹的名称。 因为使用了try-with-resources,在try块完成时,系统将在stream上调用close,然后在底层DirectoryStream上调用close。

src/main/java/collectors src/main/java/concurrency src/main/java/datetime
...
src/main/java/Summarizing.java src/main/java/tasks src/main/java/UseFilenameFilter.java

list方法的签名显示返回类型为Stream ,其参数为目录:

public static Stream<Path> list(Path dir) throws IOException

在非目录资源上执行该方法将导致NotDirectoryExcep
tion。Javadocs指出,结果流是弱一致性的,这意味着“它是线程安全的,但在迭代时不会冻结目录,因此它可能(也可能不会)反映从此方法返回后发生的目录更新。”

评论

此博客中的热门博文

D3js Data-binding basics

JavaScript 数据类型

Vue3新特性(1) —— Vite