Path
This library introduces path types for working with file paths in a structured and type-safe manner, supporting Unix (POSIX) and Windows file systems. All Path types are extension types of string, so they are zero runtime cost.
Types
Path - A platform
dependent path type - uses WindowPath
on windows and UnixPath
on all other platforms.
UnixPath - A Unix path type.
WindowsPath - A Windows path type.
Basic Operations
Create a path and perform basic operations:
import 'package:rust/rust.dart';
void main() {
var path = UnixPath('/foo/bar/baz.txt');
print('File name: ${path.fileName()}'); // Output: baz.txt
print('Extension: ${path.extension()}'); // Output: txt
print('Is absolute: ${path.isAbsolute()}'); // Output: true
var parent = path.parent();
if (parent != null) {
print('Parent: $parent'); // Output: /foo/bar
}
var newPath = path.withExtension('md');
print('New path with extension: $newPath'); // Output: /foo/bar/baz.md
}
Extracting Components
Get the components of a path:
void main() {
var path = UnixPath('/foo/bar/baz.txt');
var components = path.components().toList();
for (var component in components) {
print(component); // Output: /, foo, bar, baz.txt
}
}
Ancestors
Retrieve all ancestors of a path:
void main() {
var path = UnixPath('/foo/bar/baz.txt');
for (var ancestor in path.ancestors()) {
print(ancestor);
// Output:
// /foo/bar/baz.txt
// /foo/bar
// /foo
// /
}
}
File System Interaction
Check if a path exists and get metadata:
void main() {
var path = UnixPath('/foo/bar/baz.txt');
if (path.existsSync()) {
var metadata = path.metadataSync();
print('File size: ${metadata.size}');
print('Last modified: ${metadata.modified}');
} else {
print('Path does not exist.');
}
}