Managing Files And Directories

Manage files and directories

For complete API documentation refer to: pub.dev

DCli provides a complete set of tools for manipulating files and directories.

DCli also includes the paths package that provides tools for manipulating file paths.

A fundamental task of most CLI applications is the management of files and directories. DCli provides a large set of tools for file management.

pwd

The getter 'pwd' returns the present working directory.

print(pwd);
> /home/me

Whilst you can change your working directory we don't recommend it. Read the section on the evils of cd.

If you think you need to change your working directory check to see if the DCli function takes a 'workingDirectory' argument.

If you need to spawn another CLI application that needs to run in a specific directory use the 'start' function.

'ls'.start(workingDirectory: HOME);

If you really think you have no alternative (you are probably wrong) the you can use the Dart method Directory.current.

Find

The find command lets you explore your file system by searching for files that match a glob (wildcard).

List<String> results = find('[a-z]*.jpg').toList();

The find command starts from the present working directory (pwd) searching for any files that start with the lowercase letters a-z and ending with the extension '.jpg'.

The default action of find is to do a recursive search.

List<String> results = find('[a-z]*.jpg', workingDirectory: '\' ).toList();

If you need to do a search starting from a location other than you current directory you can use the 'workingDirectory' argument which controls where the find starts searching from.

List<String> results = find('[a-z]*.jpg', workingDirectory: '\', hidden: true ).toList();

The find command will ignore hidden files (those starting with a '.') and directories. If you need to scan hidden files then pass 'hidden: true'. If you need to return directories as well as files then use the 'types' argument.

var progress = Progress((file) => print(file));
find('*.jpg', root: '\'
  , types:[Find.directory, Find.file]
  , progress: progress);

If you are process a large amount of results you may want to process them as you go rather than waiting for the full result list to be available.

By passing a 'Progress' into 'find' your progress will be called each time a matching file is found allowing to display the progressive results to the user.

fileList

Returns the list of files and directories in the current working directory. Use the 'find' function to get a list of any other directory.

List<String> entities = fileList;

copy

The copy function copies a single file to a to a directory or a new file.

copy("/tmp/fred.text", "/tmp", overwrite=true);
copy("/tmp/fred.text", "/tmp/fred2.text", overwrite=true);

The first example will copy the file 'fred.text' to the '/tmp' directory, the second file also copies the file to the '/tmp' directory but renames the file as it goes.

If the 'overwrite' is not passed or is set to false (the default) an attempt to copy over an existing file will cause a 'CopyException' to be thrown.

copyTree

The copyTree function allows you to copy an entire tree or selected files from the tree to another location.

The copyTree function takes an optional 'filter' argument which allows you to selectively copy files. Only those files that match the filter are copied.

copyTree("/tmp", "/tmp/new_dir", overwrite:true, includeHidden:true
   , filter: (file) => extension(file) == 'dart');

The above copyTree only copies files from '/tmp' that have an '.dart' extension.

move

The move function copies a single file to a directory or a file. If the 'to' argument is a file then the file is renamed.

The move function tries to use the native OS 'rename' function however if the destination is on a different device the rename will fail. In this case the move function performs a copy then delete.

move('/tmp/fred.txt', '/tmp/folder/tom.txt');

moveTree

The moveTree function allows you to move an entire tree or selected files from the tree to another location.

The moveTree function takes an optional 'filter' argument which allows you to selectively move files. Only those files that match the filter are moved.

moveTree("/tmp/", "/tmp/new_dir", overwrite: true
   , filter: (entity) {
   var include = extension(entity) == 'dart';
   if (include) {
     print('moving: $file');
   }
  return include;
);

Like the move function the moveTree attempts an OS level rename but if that fails it resorts to performing a copy followed by a delete.

delete

The delete function deletes a file.

delete("/tmp/test.fred", ask: true);

If you pass the 'ask' argument to the delete function then the user will be prompted to confirm the delete action.

deleteDir

The deleteDir function deletes a directory.

deleteDir("/tmp/testing";

If the directory isn't empty then a DeleteDirException will be thrown.

You can delete an entire directory tree using the recursive option:

deleteDir("/tmp/testing", recursive=true);

createDir

The createDir function creates a directory. If the directory already exists then a CreateDirException will be thrown.

if (!exists('/tmp/fred/tools')) {
    createDir("/tmp/fred/tools");
}

If the parent path doesn't exists then a CreateDirException will be thrown, to avoid this pass the recursive argument

createDir("/tmp/fred/tools", recursive: true);

touch

The touch function updates the last modified date/time stamp of the passed file. If the 'create' argument is passed and the file doesn't exists then the file will be created. If the file doesn't exists and 'create: true' isn't passed then a 'TouchException' will be thrown.

touch('fred.txt, create: true');

exists

The 'exists' function checks if a file, directory or symlink exists.

if (exists("/fred.txt"))

isWritable

Test if a file or directory is writable.

if (isWritable('/fred.txt'))

isReadable

Test if a file or directory is readable.

if (isReadable('/fred.txt'))

isExecutable

Test if a file or directory is executable.

if (isExecutable('/fred.txt'))

isFile

Test if the given path is a file.

if (isFile('/fred.txt'))

Test if the given path is a symbolic link.

if (isLink('/fred.txt'))

isDirectory

Test if the given path is a directory.

if (isDirectory('/fred.txt'))

setModified

Sets the last modified date/time stamp on give path.. This is similar to touch exception that you can choose the date/time.

setLastModifed('/fred.txt', DateTime.now());

lastModified

Returns a DateTime reflecting the last modified date/time stamp of the given path.

DateTime modified = lastModifed('/fred.txt');

calculateHash

Calculates the sha256 hash of a file's content generating essentially a unique signature or checksum for the file.

This is likely to be an expensive operation if the file is large. You can use this method to check if a file has changes since the last time you took the file's hash.

var digest = calculateHash('/fred.txt');

Last updated