DART FILE OPERATIONS(Flutter)

DART FILE OPERATIONS(Flutter)

While programming, you might run into some sort of situation, where you need to work on a file stored at a specific location, maybe write something on it, read it or anything else. Dart supports working with files as well.

In order to start working, first of all we need to import dart’s inbuilt io (input output) library.

import 'dart:io';

This library gives us access to a large number of classes, methods and properties which we can use to perform various operations. In current situation, we need to work with files, hence, we need to create an instance of the File class.

main () async {  
 final file = File('test.log');  
 // some operation  
}

Most methods in this class occur in synchronous and asynchronous pairs, for example, readAsString and readAsStringSync. Unless you have a specific reason for using the synchronous version of a method, prefer the asynchronous version to avoid blocking your program.

Common File Operations

Following are some of the most useful methods we can call upon our File instance:

  • create() : Creates a file at the given location. Takes a named parameter called recursive which creates path if it doesn’t exists already.

await file.create(recursive: true);

  • rename() : Renames the file upon which method is called. Replaces file with a similar name if exists in the given path. You can use it to move files as well.

await file.rename('renamed.log');

  • copy() : Copies the file upon which method is called into the given path. Replaces file with a similar name if exists in the given path.

await file.copy('copied.log');

  • delete() : Deletes the file/directory upon which called. If target is an empty directory, it must be empty. Takes a named parameter called recursive which can be set to true to delete everything inside the path.

await file.delete();

  • exists() : Verifies if the given path exists. Returns a boolean.

await file.exists();

Reading and Writing a File

Methods which allows us to read and write a file also exists in the same File class. Here are some of the most useful methods:

  • readAsString() : Reads a file and returns its contents as a String. Takes a named parameter called encoding which accepts formats described in Encoding class.

String file = await file.readAsString();

  • readAsLines() : This method also reads the file upon which it is called, but returns the content in a List. Similarly it also accepts encoding as a named parameter.

List file = await file.readAsLines();

  • writeAsString() : Writes the given string to a file. This method takes the content to write as a positional parameter. It also accepts 3 named parameters namely mode, encoding and flush. By default, this method creates a new file and writes in it. However, this behavior can be changed with the mode parameter. Accepted list of modes can be seen in FileMode class.

await file.writeAsString('I am Batman!');

While I have not covered each and every method and property available, I tried to make sure I cover the most useful ones. There are still a lot of them remaining. Make sure you checkout the whole class’s documentation once before you jump into playing with it.

Read File In Dart

Assume that you have a file named test.txt in the same directory of your dart program.

Welcome to test.txt file.
This is a test file.

Now, you can read this file using File class and readAsStringSync() method.

// dart program to read from file
import 'dart:io';

void main() {
  // creating file object
  File file = File('test.txt');
  // read file
  String contents = file.readAsStringSync();
  // print file
  print(contents);
}

Get File Information

In this example below, you will learn how to get file information like file location, file size, and last modified time.

import 'dart:io';

void main() {
  // open file
  File file = File('test.txt');
  // get file location
  print('File path: ${file.path}');
  // get absolute path
  print('File absolute path: ${file.absolute.path}');
  // get file size
  print('File size: ${file.lengthSync()} bytes');
  // get last modified time
  print('Last modified: ${file.lastModifiedSync()}');
}

Write File In Dart

Let’s create a file named test.txt in the same directory of your dart program and write some text in it.

// dart program to write to file
import 'dart:io';

void main() {
  // open file
  File file = File('test.txt');
  // write to file
  file.writeAsStringSync('Welcome to test.txt file.');
  print('File written.');
}

Add New Content To Previous Content

You can use FileMode.append to add new content to previous content. Assume that test.txt file already contains some text.

Welcome to test.txt file.

Now, let’s add new content to it.

// dart program to write to existing file
import 'dart:io';

void main() {
  // open file
  File file =  File('test.txt');
  // write to file
  file.writeAsStringSync('\nThis is a new content.', mode: FileMode.append);
  print('Congratulations!! New content is added on top of previous content.');
}

Delete File In Dart

Assume that you have a file named test.txt in the same directory of your dart program. Now, let’s delete it.

// dart program to delete file
import 'dart:io';

void main() {
  // open file
  File file = File('test.txt');
  // delete file
  file.deleteSync();
  print('File deleted.');
}

Delete File If Exists

You can use File.existsSync() method to check if a file exists or not. If it exists, then you can delete it.

// dart program to delete file if exists
import 'dart:io';

void main() {
  // open file
  File file = File('test.txt');
  // check if file exists
  if (file.existsSync()) {
    // delete file
    file.deleteSync();
    print('File deleted.');
  } else {
    print('File does not exist.');
  }
}

THANK YOU!