Flutter 파일 문자열 저장, 제어

야민·2022년 7월 19일

파일 저장 순서

  1. 저장 경로 찾기
  2. 파일 경로에 대한 참조 생성
  3. 파일에 데이터 쓰기
  4. 파일의 데이터 읽기

1. 저장 경로 찾기

path_provider 플러그인을 사용하여 기기의 파일 시스템에서 사용되는 경로에 접근할 수 있습니다.

  • 임시 디렉토리 경로
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
  • 문서 디렉토리 경로
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;

2. 파일 경로에 대한 참조 생성

dart:io 라이브러리에서 제공하는 File 클래스를 사용하여 파일을 제어할 수 있습니다.

Future<File> _localFile(String morePath) async {
  Directory appDocDir = await getApplicationDocumentsDirectory();
  final path = await appDocDir.path + '/$morePath';
  return File('$path');
}
  • 해당 파일의 상위 경로가 완성되지 않았을 경우 경로의 유무를 확인해야 합니다.
var directoryPaths = path.split('/');
directoryPaths.removeLast();
final Directory _appDocDirFolder = Directory('${directoryPaths.join('/')}/');

if (!_appDocDirFolder.existsSync())
      await _appDocDirFolder.create(recursive: true);

3. 파일에 데이터 쓰기

final file = await _localFile();
file.writeAsString('hello world');

4. 파일의 데이터 읽기

Future<String> readFileAsString() async {
    try {
      final file = await _localFile('cache/test.txt');
      String data = await file.readAsString();
      return data;
    } catch (e) {
      return null;
    }
  }

0개의 댓글