0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DartでopenReadを使ってファイルを読み込む方法

Posted at

概要

Dartにおけるファイル読み込み方法のうち、FileopenReadメソッドを使った方法を紹介します。

他の記事では一発で知りたいことが書いてありますが、ここでは一つづつ処理を追い、どうしてそのような書き方にするのかを明確にします。

基本的な書き方

example.dart
import 'dart:convert';
import 'dart:io';

void main(List<String> arguments) async {
  var file = File(arguments[0]);  
  var lines = file.openRead();

  await for (var line in lines) {
    print(line);
  }
}
コード 説明 APIリファレンス
void main(List arguments) async 引数として文字列リストを受け取ります。関数内でファイルをopenReadStreamを扱うため、asyncを付与します。
var file = File(arguments[0]); 引数を使ってFileクラスのインスタンスを作ります。arguments[0]にはファイルパスを渡す想定です。
var lines = file.openRead(); FileクラスのopenReadメソッドを使用します。このメソッドによる返り値はStreamです。 openRead abstract method
await for (var line in lines) Streamを読み込むためにawait forを使用します。
print(line) 読み込んだファイルの行をコンソールへ出力します。
出力結果
[47, 47, 32, 105, 109, 112, 111, 114, 116, 32, 39, 112, 97, 99, 107, 97, 103, 101, 58, 99, 108]

単純にopenReadだけではバイト列として表示されます。

UTF8へデコードして表示する

example.dart
import 'dart:convert';
import 'dart:io';

void main(List<String> arguments) async {
  var file = File(arguments[0]);
+ var lines = utf8.decoder
+     .bind(file.openRead());

  await for (var line in lines) {
    print(line);
  }
}
コード 説明 APIリファレンス
utf8.decoder.bind(file.openRead()) UTF8へデコードするためにutf8.decoder.bind()を使用します。 bind method
出力結果
これはhogehogeです。
# コメント hugahuga

このように人間が読める文字列となります。

一行づつ処理を行う

上記の例ではlinesというStreamにすべての文字列が含まれています。

lines
lines = ["これはhogehogeです。\n# コメント hugahuga", "", ...]

#によってコメントアウトされた行だけを除き出力したい場合は、一行づつ処理を行います。次のように改行文字でStreamを分割し新しいStreamとします。

example.dart
import 'dart:convert';
import 'dart:io';

void main(List<String> arguments) async {
  var file = File(arguments[0]);
  var lines = utf8.decoder
      .bind(file.openRead())
+     .transform(const LineSplitter());

  await for (var line in lines) {
+   if (!line.startsWith("#")) print(line);
  }
}
コード 説明 APIリファレンス
.transform(const LineSplitter()) LineSplitter()というStreamトランスフォーマーによってStreamを改行文字列で分割する LineSplitter class
if (!line.startWith("#")) print(line) startWith()で先頭が#になっている行を検出するようにしている。 startsWith abstract method
出力結果
これはhogehogeです。

先頭に#がある行は出力されなくなります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?