LibAC-dart/lib/utils/IOTools.dart

124 lines
2.6 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
class PathHelper {
String pth = "";
PathHelper({required this.pth});
static String combine(String path1, String path2) {
return path1 + Platform.pathSeparator + path2;
}
static PathHelper builder(String startPath) {
return PathHelper(pth: startPath);
}
bool exists() {
File fi = File(build());
Directory dir = Directory(build());
return fi.existsSync() || dir.existsSync();
}
PathHelper clone() {
return PathHelper.builder(build());
}
PathHelper resolve(String path2) {
pth += Platform.pathSeparator + path2;
return this;
}
PathHelper conditionalResolve(bool flag, String path) {
if (flag) pth += Platform.pathSeparator + path;
return this;
}
bool deleteDirectory({bool recursive = false}) {
Directory dir = new Directory(build());
try {
dir.deleteSync(recursive: recursive);
return true;
} catch (E) {
return false;
}
}
bool deleteFile() {
File file = new File(build());
try {
file.deleteSync(recursive: true);
return true;
} catch (E) {
return false;
}
}
PathHelper removeDir() {
deleteDirectory(recursive: true);
return this;
}
PathHelper removeFile() {
deleteFile();
return this;
}
PathHelper mkdir() {
Directory dir = new Directory(build());
dir.createSync(recursive: true);
return this;
}
String build() {
return pth;
}
}
Stream<List<int>> tail(final File file) async* {
final randomAccess = await file.open(mode: FileMode.read);
var pos = await randomAccess.position();
var len = await randomAccess.length();
// Increase/decrease buffer size as needed.
var buf = Uint8List(8192);
Stream<Uint8List> _read() async* {
while (pos < len) {
try {
final bytesRead = await randomAccess.readInto(buf);
pos += bytesRead;
yield buf.sublist(0, bytesRead);
} catch (E) {}
}
}
// Step 1: read whole file
yield* _read();
// Step 2: wait for modify events and read more bytes from file
await for (final event in file.watch(events: FileSystemEvent.modify)) {
if ((event as FileSystemModifyEvent).contentChanged) {
try {
len = await (randomAccess.length());
yield* _read();
} catch (E) {}
}
}
}
void tailAndPrint(File file) {
try {
tail(file)
.transform(utf8.decoder)
.transform(LineSplitter())
.forEach((line) {
// Do something with the line that has been read, e.g. print it out...
print(line);
});
} catch (E) {}
}