38

How do you read text from a file and write text to a file?

I've been learning about how to read and write text to and from a file. I found another question about reading from assets, but that is not the same. I will add my answer below from what I learned from the documentation.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

4 Answers4

69

Setup

Add the following plugin in pubspec.yaml:

dependencies:
  path_provider: ^1.6.27

Update the version number to whatever is current.

And import it in your code.

import 'package:path_provider/path_provider.dart';

You also have to import dart:io to use the File class.

import 'dart:io';

Writing to a text file

_write(String text) async {
  final Directory directory = await getApplicationDocumentsDirectory();
  final File file = File('${directory.path}/my_file.txt');
  await file.writeAsString(text);
}

Reading from a text file

Future<String> _read() async {
  String text;
  try {
    final Directory directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/my_file.txt');
    text = await file.readAsString();
  } catch (e) {
    print("Couldn't read file");
  }
  return text;
}

Notes

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 1
    I used _read function But I get this problem: "The function 'File' isn't defined." – Heyran.rs Feb 11 '19 at 20:04
  • 2
    @Heyran.rs You need to import `dart:io`. In Android Studio you can put the cursor on `File` and press Option+Return in Mac or Alt+Enter in Linux/Windows to add it automatically from a menu. – Suragch Feb 11 '19 at 20:52
  • Thank you. Now I get another problem. It returns "Couldn't read file". My assets is: <- data/table.txt>. I only replace my_file.txt to table.txt in _read methode. – Heyran.rs Feb 12 '19 at 14:14
  • @Heyran.rs, I'm not sure why. I can only suggest that you step through in debugging mode and try to isolate where the error is. Also, print the error message in the catch block. If you still can't solve it, then try asking a new question with all these details included. – Suragch Feb 12 '19 at 16:38
  • How to know where this my_file is stored? Can I access it manually? – Iván Yoed Feb 24 '21 at 18:21
  • Is it possible to change the storage location, because what if I want to run this on linux or web? Actually I did try, and it crashes, because `getApplicationDocumentsDirectory` works only for android and iOS by accessing to their local folders. I wonder if there's a way to change the root folder for the new directory. – Iván Yoed Feb 24 '21 at 22:42
  • @IvánYoed, good question. I haven't done this yet. If you find the answer please leave a comment or another answer. – Suragch Feb 25 '21 at 00:13
  • 1
    Sure, I think this could be a solution. I'll be testing it myself to check if indeed it is https://pub.dev/packages/path_provider_linux. It implements the package:path_provider functionality for linux. – Iván Yoed Feb 25 '21 at 04:14
  • 1
    As I intended to, I tested the `path_provider` package on Linux. I confirmed that this package has already support for it, so this "read and write" practice on flutter for desktop on linux does work. The crash was on flutter for web. By the way, the directory for the created `.txt` in my case was at Documents. – Iván Yoed Feb 25 '21 at 19:32
  • 1
    @IvánYoed, Thank you for the updates. I also added a note to my answer. – Suragch Feb 25 '21 at 23:46
  • I do have a question and maybe you've already occupied yourself with this topic. I share with you the post, related to the same features named in your post. Here it is: https://stackoverflow.com/questions/66394148/flutter-delete-certain-amount-of-characters-of-a-txt-file – Iván Yoed Feb 27 '21 at 04:18
  • @IvánYoed, sorry, I'm not sure. I don't have time to work on it right now. – Suragch Feb 27 '21 at 06:03
  • No worries. I'll keep it up with my research and as soon as I find something, I'll be sharing it with the community. – Iván Yoed Mar 01 '21 at 05:39
  • I couldn't get the file write to work at first, it only ever seemed to write a single line to the file when called multiple times in a loop. Then I realised I was missing the await keyword from the line "await file.writeAsString". For some reason it doesn't work correctly without using await - maybe there's some file locking going on or something and it trips over itself. – VincentH May 01 '23 at 10:55
5

As additional info to @Suragch's answer, if you want to find the file you created, you can do as the images show:

enter image description here

And then inside that data folder, go again to a folder named data and search for your package, and then go to:

enter image description here

If you happen to create new files, in order to be able to see them, just right click and click Synchronize.

enter image description here

Iván Yoed
  • 3,878
  • 31
  • 44
  • 1
    If you don't see *Device File Explorer* you can check the Event Log and see if you can configure Android Framework based on your AndroidManifest.xml files, after this, you will see *Device File Explorer* under _View -> Tools Windows_ – Philipos D. Mar 11 '21 at 09:23
0

An another way to pull the file from the device is by using adb pull command. You can find the file path by debugging the code and then use adb pull command. adb is located in Android SDK -> platform-tools directory.

./adb pull /storage/emulated/0/Android/data/com.innovate.storage.storage_sample/files/sample.txt ~/Downloads
0

@Suragch 's answer is right. Except the version of path_provider that you want to use now is:

path_provider: ^2.0.9

Sagar
  • 23
  • 5
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31690527) – Chukwuemeka Ihedoro May 09 '22 at 09:21