gpt4 book ai didi

dart recipe file.rename() 重命名文件但不更新对象中的路径

转载 作者:行者123 更新时间:2023-12-03 02:53:34 24 4
gpt4 key购买 nike

dart 食谱“重命名文件、目录或符号链接(symbolic link)”,位于 https://www.dartlang.org/dart-vm/dart-by-example#renaming-a-file-directory-or-symlink似乎没有按预期工作:

import 'dart:io';

main() async {
// Get the system temp directory.
var systemTempDir = Directory.systemTemp;

// Create a file.
var file = await new File('${systemTempDir.path}\\foo.txt').create();

// Prints path ending with `foo.txt`.
print('The path is ${file.path}');

// Rename the file.
await file.rename('${systemTempDir.path}\\bar.txt');

// Prints path ending with `bar.txt`.
print('The path is ${file.path}');
}

输出显示文件对象的内部路径字段没有改变(虽然重命名成功):
[Running] dart "d:\src\dart\renameAsOnWeb.dart"
The path is C:\Users\guivh\AppData\Local\Temp\foo.txt
The path is C:\Users\guivh\AppData\Local\Temp\foo.txt

[Done] exited with code=0 in 0.327 seconds

我已经扩展/修改了食谱示例以进一步调查:
import 'dart:io';

main() async {
var systemTempDir = Directory.systemTemp;
var file = await new File('${systemTempDir.path}\\foo.txt').create();
print('The file is located at ${file.path}');
File toDelete;

var newName = '${systemTempDir.path}\\fubar.toodeloo';
await file.rename(newName);

if (await new File(newName).exists() == false) {
print('The rename failed: there is no ${newName} file');
} else {
var newFile = new File(newName);
print('The rename was succesful');
var nameChangedInObject = file.path == newName;
if (nameChangedInObject) {
print('The path of the file object has changed correctly');
toDelete = newFile;
} else {
print(
'The path in the file object still is: ${file.path}');
toDelete = newFile;
}
await toDelete.delete();
print(
'And now, ${toDelete.path} is gone: ${await toDelete.exists() == false}');
}
}

此输出证实了内部路径字段未使用新名称更新的事实:
[Running] dart "d:\src\dart\renamingExample.dart"
The file is located at C:\Users\guivh\AppData\Local\Temp\foo.txt
The rename was succesful
The path in the file object still is: C:\Users\guivh\AppData\Local\Temp\foo.txt
And now, C:\Users\guivh\AppData\Local\Temp\fubar.toodeloo is gone: true

[Done] exited with code=0 in 0.369 seconds

我在 Windows 盒子上运行开发版本:
PS D:\src\dart> dart --version
Dart VM version: 2.0.0-dev.39.0 (Fri Mar 16 00:17:07 2018 +0100) on "windows_x64"
PS D:\src\dart>

有人可以解释一下这里发生了什么吗?

最佳答案

这个例子是错误的。 File对象 is immutable ,所以它肯定不会被重命名操作改变。这个例子的期望是错误的。

关于dart recipe file.rename() 重命名文件但不更新对象中的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com