파일 시스템 작업
기기의 파일 시스템에서 데이터를 읽고 쓰는 방법을 학습해 더 큰 파일과 사용자 지정 데이터 형식을 저장합니다.
파일 시스템 작업은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Storing Data in Files
Sometimes, your app needs to store data directly on the device. This is where file system operations come in! Unlike shared_preferences (for small key-value data) or sqflite (for structured data), file system operations allow you to manage files directly.
You can store larger pieces of data, like images, audio, or custom formatted text files, that don't fit well into a database or simple key-value pairs.
Where to Store Files?
Before you can read or write files, your app needs to know where it can store them. Flutter provides the path_provider package to help you find common directory paths safely across different platforms (iOS, Android, web, desktop).
- Application Documents Directory: This is where your app can store user-specific data that should persist.
- Temporary Directory: For data that doesn't need to persist across app launches, like cached files.
Getting Application Path
Let's use path_provider to get the application documents directory. Remember to add path_provider to your pubspec.yaml first!
dependencies:
flutter:
sdk: flutter
path_provider: ^2.0.11
import 'dart:io';
import 'package:path_provider/path_provider.dart';
void main() async {
// Get the application documents directory
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
print('App Documents Path: $appDocPath');
}Creating a File Reference
Once you have a directory path, you can create a File object. This object represents the file at that specific path on the device's storage. It doesn't mean the file actually exists yet, it's just a reference.
You'll combine the directory path with your desired filename to construct the full file path.
Constructing a File Path
Here's how you can combine the application documents path with a filename to create a File object. We'll use a simple text file name for our example.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
void main() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
// Define a filename
String fileName = 'my_data.txt';
// Create a File object
File file = File('$appDocPath/$fileName');
print('File path reference created: ${file.path}');
// At this point, the file might not exist on disk yet.
}Saving Content to Files
The File object provides methods to write data. The most common ones are writeAsString() for text and writeAsBytes() for binary data. These operations are asynchronous, so you'll use await.
writeAsString(String contents, {FileMode mode = FileMode.write}): Writes text.FileMode.writeoverwrites,FileMode.appendadds to the end.writeAsBytes(List<int> bytes, {FileMode mode = FileMode.write}): Writes raw bytes.
Writing a Simple Text File
Let's write some text content to our my_data.txt file. If the file doesn't exist, writeAsString will create it. If it does exist, it will overwrite its content by default.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
void main() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
String fileName = 'my_data.txt';
File file = File('$appDocPath/$fileName');
String content = 'Hello, CoddyKit learners!\nThis is a test message.';
try {
await file.writeAsString(content);
print('Content written to ${file.path}');
print('File exists: ${await file.exists()}');
} catch (e) {
print('Error writing file: $e');
}
}Reading Content from Files
Just as you can write, you can also read content back from files. The readAsString() method is perfect for text files, while readAsBytes() is used for binary data.
It's good practice to check if a file exists() before trying to read from it to prevent errors.
Reading a File's Content
Now, let's read the content we just wrote back from my_data.txt. We'll first check if the file exists to be safe.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
void main() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
String fileName = 'my_data.txt';
File file = File('$appDocPath/$fileName');
if (await file.exists()) {
try {
String content = await file.readAsString();
print('Content read from ${file.path}:\n$content');
} catch (e) {
print('Error reading file: $e');
}
} else {
print('File does not exist: ${file.path}');
}
}Removing Files
When data is no longer needed, you can delete files from the device's storage. The delete() method on a File object will remove it. This operation is also asynchronous.
Be careful when deleting files, as this action is usually irreversible!
Check Your Understanding
Which of the following statements about Flutter file system operations are TRUE?
Lesson Summary
Great job! In this lesson, you've learned how to interact with the device's file system in Flutter:
- Used
path_providerto find appropriate storage directories. - Created
Fileobjects to reference specific files. - Wrote content to files using
writeAsString(). - Read content from files using
readAsString(). - Understood how to delete files with
delete().
File system operations are crucial for storing large, custom-formatted, or sensitive data directly on the device. Next, you can explore more advanced data handling or move on to other Flutter topics!
자주 묻는 질문
“파일 시스템 작업” 강의는 무료인가요?
네 — “파일 시스템 작업” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“파일 시스템 작업”에서 뭘 배우나요?
기기의 파일 시스템에서 데이터를 읽고 쓰는 방법을 학습해 더 큰 파일과 사용자 지정 데이터 형식을 저장합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“파일 시스템 작업” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.