Reputation: 2667
given the code below
import 'dart:convert';
import 'dart:io';
void main() {
print('open file');
final path = stdin.readLineSync(encoding: utf8);
if (path == null) {
throw Exception('no path provided');
}
final uri = Uri.tryParse(path);
if (uri == null) {
throw Exception('invalid uri');
}
final file = File.fromUri(uri);
if (file.existsSync()) {
print(file.readAsStringSync());
return;
}
throw ('file not found: ${uri.path}');
}
if I run the commands below
dart run bin/console_test.dart
open file
~/Desktop/test_folder/readme.md
I get the error file not found: ~/Desktop/test_folder/readme.md
but a normal cat
command open the file easily
cat ~/Desktop/test_folder/readme.md
hello world!%
what am I missing?
Upvotes: 1
Views: 48
Reputation: 2667
here is a workaround based on this answer
import 'dart:convert';
import 'dart:io' as io;
import 'package:path/path.dart' as path;
void main() {
print('open file');
final maybePath = io.stdin.readLineSync(encoding: utf8);
if (maybePath == null) {
throw Exception('no path provided');
}
final maybeRoot = io.Platform.isWindows
? io.Platform.environment['USERPROFILE']
: io.Platform.environment['HOME'];
if (maybeRoot == null) {
throw Exception('no root found');
}
final pathSegments = maybePath.split('');
if (pathSegments.first == '~') {
pathSegments.removeAt(0);
}
final realPath = path.absolute([maybeRoot, ...pathSegments].join());
final uri = Uri.tryParse(realPath);
if (uri == null) {
throw Exception('could not find root');
}
final file = io.File(uri.toFilePath(windows: io.Platform.isWindows));
if (file.existsSync()) {
print(file.readAsStringSync());
return;
}
throw ('file not found: ${file.path}');
}
Upvotes: 1