[flutter] 플러터에서 앱 라이브러리 디렉토리에 파일 읽기

플러터(Flutter) 앱 개발 중에는 종종 앱 라이브러리 디렉토리에 저장된 파일을 읽어와야 하는 경우가 있습니다. 예를 들어 앱 설정 파일, 데이터베이스 파일 등을 앱 라이브러리 디렉토리에 저장하고 이를 읽어와야 할 수도 있습니다.

앱 라이브러리 디렉토리 경로 가져오기

플러터에서는 path_provider 패키지를 사용하여 앱 라이브러리 디렉토리 경로를 가져올 수 있습니다. 이를 위해 다음과 같은 단계를 따르세요:

  1. pubspec.yaml 파일에 path_provider 패키지를 추가합니다: ```yaml dependencies: flutter: sdk: flutter

path_provider: ^2.0.1


2. `pubspec.yaml` 파일을 저장한 후, 패키지를 가져오기 위해 터미널에서 `flutter pub get` 명령을 실행합니다.

3. 다음 코드를 사용하여 앱 라이브러리 디렉토리 경로를 가져옵니다:
```dart
import 'dart:io';
import 'package:path_provider/path_provider.dart';

Future<String> getLibraryDirectoryPath() async {
  Directory appLibraryDir = await getLibraryDirectory();
  return appLibraryDir.path;
}

파일 읽기

파일 읽기를 위해서는 dart:io 패키지의 File 클래스를 사용해야 합니다. 앱 라이브러리 디렉토리 경로를 가져온 후, File 클래스를 사용하여 파일을 읽을 수 있습니다. 아래는 파일을 읽는 예제 코드입니다:

import 'dart:io';
import 'package:path_provider/path_provider.dart';

Future<File> getFile(String fileName) async {
  Directory appLibraryDir = await getLibraryDirectory();
  String filePath = '${appLibraryDir.path}/$fileName';
  return File(filePath);
}

Future<String> readFile(String fileName) async {
  File file = await getFile(fileName);
  if (!await file.exists()) {
    throw Exception('File does not exist');
  }
  return await file.readAsString();
}

// 사용 예시
void main() async {
  try {
    String contents = await readFile("myFile.txt");
    print(contents);
  } catch (e) {
    print('Error reading file: $e');
  }
}

위의 예제 코드에서는 getFile 함수를 통해 파일 객체를 생성한 후, readFile 함수를 호출하여 파일을 읽고 그 내용을 출력합니다.

이제 플러터 앱에서 앱 라이브러리 디렉토리에 저장된 파일을 읽는 방법을 알게 되었습니다. 필요에 따라 위의 코드를 수정하고 활용하여 원하는 기능을 구현할 수 있습니다.