Home > Back-end >  Update sepcific line in file
Update sepcific line in file

Time:09-18

Hi is there a method from which I can update a specific line in a file. My file has data seperated by line break

Sample example to delete line but I have to write everything into file again, can I perform CRUD opertion directly on file lines ?

I want to update specific line in file wihout reading entire file => update string and => write all lines to file.

I may switch to any kind of file type that can offer me this functionality. Is there a way to store data in row column architecture like sql ?

import 'dart:io';

Future<void> myAsyncFunction() async {
  const index = 5;
  final File f = File('test.txt');
  final List<String> lines = await f.readAsLines();
  lines.removeAt(index);
  await f.writeAsString(lines.join('\n'));
}

CodePudding user response:

This should be possible by using the String Scanner library, it provides a class called LineScanner and LineScannerState through which you can set the position.

I have not tried this for the exact use case you mention above, so please do evaluate it for your use-case

CodePudding user response:

Files are stored as a contiguous array of bytes on a disk, there is no way to remove a specific line without scanning for newlines and shifting trailing data to fill the void.

For a more sophisticated way of storing data there are many popular database packages, including sqflite, hive, drift, sembast, and objectbox.

  • Related