You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart程序无法找到~开头的已存在文件,cat命令可正常访问,求解答

问题:Dart程序无法识别带~的文件路径,而cat命令可正常访问

你编写了以下Dart代码用于读取指定路径的文件:

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}');
}

执行程序时输入带~的路径:

dart run bin/console_test.dart
open file
~/Desktop/test_folder/readme.md

程序报错:

file not found: ~/Desktop/test_folder/readme.md

但使用cat命令却能正常打开该文件:

cat ~/Desktop/test_folder/readme.md
hello world!%

请问我忽略了什么?


原因与解决方法

  • ~是Shell的特殊标识符,代表当前用户的主目录,只有Shell会自动将其解析为实际的主目录路径(比如/home/username)。Dart的Uri.tryParse和File类不会处理这个特殊字符,会直接把~当作路径的一部分,导致找不到对应的文件。
  • 解决方法:手动将路径中的~替换为当前用户的主目录路径。可以通过Platform.environment['HOME']获取系统环境变量中的主目录路径,再完成替换。

修改后的代码示例:

import 'dart:convert';
import 'dart:io';

void main() {
  print('open file');
  var path = stdin.readLineSync(encoding: utf8);
  if (path == null) {
    throw Exception('no path provided');
  }
  
  // 解析~为用户主目录
  final homeDir = Platform.environment['HOME'];
  if (homeDir != null && path.startsWith('~/')) {
    path = path.replaceFirst('~/', '${homeDir}/');
  }

  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}');
}

内容的提问来源于stack exchange,提问作者user9836706

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:15:35