|

Dartの勉強11−1:ファイルとフォルダと同期・非同期

フォルダ間をシンクロさせるプログラムの作成に必要な機能を勉強していきます。
非同期となる処理は、asyncを入れて、処理中に非同期処理を呼び出すと終了を待たずに先に進んでしまう。

  1. 同期・非同期
    処理の完了を待たなくても先に進んでかまわない処理を含む場合は、{}の前にasyncを入れます。ただし、処理している途中で終わるのを待ってほしい処理はawaitを入れます。みた方が早いね。

    void main() async {
      print('処理1:開始');
      // 非同期処理
      Future.delayed(Duration(seconds: 2), () {
        print('処理2:非同期処理1の終了');
      });
      //これも非同期だけど上よりも早く終わるし、次に入るのはこの処理が終わってから
      await process2();
      print('処理3:完了');
    }
    
    Future<void> process2() async {
      await Future.delayed(Duration(seconds: 1), () {
        print('処理4:非同期処理2の終了');
      });
    }
    
    =処理結果=
    処理1:開始
    処理4:非同期処理2の終了
    処理3:完了
    処理2:非同期処理1の終了
    

    ということで、処理2の終了を待たずに先に進んでしまうが、処理4は待ってもらえるので、その結果を踏まえて処理3が実行される。処理2はこのプロセスでは、処理結果が使われることを前提としていない。

  2. jsonファイルの読み込みやファイルとフォルダの存在チェック
    import 'dart:convert';
    import 'dart:io';
    void main(List arguments) async { //非同期です。
      final configFile = File('folder_sync.json'); //jsonファイルを代入
      if (!await configFile.exists()) { //存在チェック:awaitの前に!が入ってちょっとびっくり
        print('Config file not found: ${configFile.path}');
        return;
      }
    
      final configContent = await configFile.readAsString(); //jsonファイルの読み込み
      final config = jsonDecode(configContent); //読み込んだファイルをMap型に変換
      final folder1 = Directory(config['folder1']); //フォルダ1を代入
      final folder2 = Directory(config['folder2']); //フォルダ2を代入
      print(folder1.existsSync()); //存在するかしないかを返す
      print(folder2.existsSync());
    }
    
    folder_sync.json
    {
    	"folder1":"/Volumes/SSD/folder1/",
    	"folder2":"/Volumes/SSD/folder2/"
    }
    
  3. 対象となるフォルダに変更が起こったかどうかを監視する機能を追加したもの
    import 'dart:convert';
    import 'dart:io';
    
    bool isRunning = true; // 停止フラグ
    void main(List arguments) async {
      //非同期です。
    
      handleExit(); //終了処理を呼び出し
    
      final configFile = File(
          '/Volumes/M4SSD/AppData/sync_folders/folder_sync.json'); //jsonファイルを代入
      if (!await configFile.exists()) {
        //存在チェック:awaitの前に!が入ってちょっとびっくり
        print('Config file not found: ${configFile.path}');
        return;
      }
    
      final configContent = await configFile.readAsString(); //jsonファイルの読み込み
      final config = jsonDecode(configContent); //読み込んだファイルをMap型に変換
      final folder1 = Directory(config['folder1']); //フォルダ1を代入
      final folder2 = Directory(config['folder2']); //フォルダ2を代入
      print(folder1.existsSync()); //存在するかしないかを返す
      print(folder2.existsSync());
    
      await watchFolder(folder1);
    }
    
    // フォルダ監視
    Future<void> watchFolder(Directory source) async {
      if (!isRunning) return; // 停止チェック
      await for (final event in source.watch()) {
        if (event is FileSystemEvent) {
          print('Change detected in ${source.path}: ${event.path}');
        }
      }
    }
    
    // 終了処理
    Future<void> handleExit() async {
      stdin.listen((input) {
        final command = String.fromCharCodes(input).trim();
        if (command.toLowerCase() == 'exit') {
          print('Stopping program...');
          isRunning = false;
        }
      });
    }
    

    Change detected in /Volumes/SSD/folder1/: /Volumes/SSD/folder1/x.txt
    みたいに、何が起こったのか表示されます。

類似投稿

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.