hhpack / file
Hack 语言文件工具库
1.2.2
2017-10-02 12:04 UTC
Requires
- hhvm: >= 3.21.0
- hhvm/hhvm-autoload: ^1.5
Requires (Dev)
- hackpack/hackunit: ^1.1
README
此包是一个用于执行简单的 hacklang 文件操作的库。
将为用户提供轻量级和简单的 API。
基本用法
可以通过以下简单代码实现文件的读取处理。
逐行读取。
use HHPack\File\FileLineStream; $lineStream = FileLineStream::fromString('/path/to/text.log'); foreach ($lineStream as $line) { echo $line->length(), "\n"; //output length echo $line->value(), "\n"; //output content };
读取 CSV 文件
use HHPack\File\FileLineStream; use HHPack\File\SeparatedRecordStream; use HHPack\File\ColumnSpecification; $spec = new ColumnSpecification(',', '"'); $spec->addColumn(0, 'name'); $spec->addColumn(1, 'description'); $lineStream = FileLineStream::fromString(__DIR__ . '/example.csv'); $csvStream = new SeparatedRecordStream($lineStream, $spec); foreach ($csvStream as $record) { echo $record->get('name'), "\n"; echo $record->get('description'), "\n"; }
自定义读取记录
将创建一个实现 ParseSpecification 的解析器。
然后使用 ParsedFileReader,然后应用解析器。
use HHPack\File\FileLineStream; use HHPack\File\ParsedChunkStream; use HHPack\File\ParseSpecification; final class CustomRecordSpecification implements ParseSpecification<array<string>> { public function parse(Chunk $line) : array<string> { return $line->split(','); } } $spec = new CustomRecordSpecification(); $lineStream = FileLineStream::fromString(__DIR__ . '/example.csv'); $csvStream = new ParsedChunkStream($lineStream, $spec); foreach ($csvStream as $values) { echo $values[0], "\n"; echo $values[1], "\n"; }
运行测试
您可以使用以下命令运行测试。
composer install
composer test