如果我有这样的脚本
import 'package:path/path.dart' as p;
import 'dart:io';
import 'dart:async';
void main() async {
final inDir = p.join(Directory.current.path, 'tmp', 'in'); // should we rename this
var dir = Directory(inDir);
final List<FileSystemEntity> fileList = await dir.list().toList();
for (var file in fileList.where((entity) => entity is File) ) {
print ("Processing ${(file as File).toString()}");
final contents = (file as File).readAsStringSync();
print (contents);
}
}
它工作正常。
Processing File: 'C:\FlutterProjects\project\tmp\a.txt'
some text
但是如果我想获取文件路径以字符串形式传递给另一个函数
import 'package:path/path.dart' as p;
import 'dart:io';
import 'dart:async';
void main() async {
final inDir = p.join(Directory.current.path, 'tmp'); // should we rename this
var dir = Directory(inDir);
final List<FileSystemEntity> fileList = await dir.list().toList();
for (var file in fileList.where((entity) => entity is File) ) {
print ("Processing ${(file as File).toString()}");
readFile ((file as File).toString());
}
}
void readFile (String filePath) {
final file = File(filePath);
final contents = file.readAsStringSync();
print (contents);
}
...那么它就不起作用了...
Processing File: 'C:\FlutterProjects\project\tmp\a.txt'
Unhandled exception:
FileSystemException: Cannot open file, path = 'File: 'C:\FlutterProjects\project\tmp\a.txt'' (OS Error: The filename, directory name, or volume label syntax is incorrect.
, errno = 123)
#0 _File.throwIfError (dart:io/file_impl.dart:675:7)
#1 _File.openSync (dart:io/file_impl.dart:490:5)
#2 _File.readAsBytesSync (dart:io/file_impl.dart:574:18)
#3 _File.readAsStringSync (dart:io/file_impl.dart:624:18)
#4 readFile (file:///C:/FlutterProjects/project/bin/parse-files.dart:18:27)
#5 main (file:///C:/FlutterProjects/project/bin/parse-files.dart:11:5)
<asynchronous suspension>
我猜是因为它仍然以 File: 开头。所以我可以将其视为函数本身中的一个实体,或者我将字符串转换为不以 File: 开头,但我不明白为什么它不将文件的字符串作为文件发送(这正是我想要做的,以使函数更具可重用性)。
((file as File).toString());
TL;DR当文件是 FileEntity 时为什么不按我期望的方式执行。