Home > database >  How I can read only a interval of a file content in flutter?
How I can read only a interval of a file content in flutter?

Time:04-13

i'm manipulating a file to store information in the app in flutter. For example purposes consider a file .txt with the following items as String:

[ value 1, value 2, value 3, value 4, ... value 500, ]

my app should be very quick in this reading, I'm looking for a way to read only a range of this file, for example from item 0 to item 20. Would you have a way to do this without throwing the entire value of the file into a var? I'd like to stop reading as soon as I've reached the limit. currently i do that way with path provider:

Future<String> load() async {
    final Directory directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/names.txt');

    return await file.readAsString();
  }

CodePudding user response:

If you want to read only portions of a file, you need random access, and thus you need to use File.open/File.openSync to obtain a RandomAccessFile:

var file = File('path/to/file');
var randomAccessFile = file.openSync();
try {
  var bytes = randomAccessFile.readSync(20); // Read the first 20 bytes.
  ...
} finally {
  randomAccessFile.closeSync();
}

Alternatively you could use File.openRead to create a Stream that reads a portion of the specified file.

  • Related