gpt4 book ai didi

java - 无法删除或重命名文件

转载 作者:行者123 更新时间:2023-12-01 12:39:25 25 4
gpt4 key购买 nike

我正在尝试删除 CVS 文件的最后一行,为此我需要重命名/删除我的输入文件,我尝试了几件事,但我无法让它工作,这就是我现在得到的:

File inputFile = new File((file.getParent() + "/ExportLijst " +  dateFormat.format(date) + ".csv"));
inputFile.setWritable(true, true);
File f = (inputFile);

if (!f.exists())
throw new IllegalArgumentException(
"Delete: no such file or directory: " + inputFile);

if (!f.canWrite())
throw new IllegalArgumentException("Delete: write protected: "
+ inputFile);


if (f.isDirectory()) {
String[] files = f.list();
if (files.length > 0)
throw new IllegalArgumentException(
"Delete: directory not empty: " + inputFile);
}

boolean success = f.renameTo(removeFile);

if (!success)
throw new IllegalArgumentException("Delete: deletion failed");

我也尝试过,但没有结果:

public void forceRename(File source, File target) throws IOException
{
if (target.exists())
target.delete();
source.renameTo(target);
}

最佳答案

很可能您没有关闭该文件,然后其他文件操作将无法在 Windows 上执行。

您为我们整理的代码片段当然不是很连贯。它们看起来不错,但需要查看上下文。有点多了。

所以尝试确保关闭:

try (PrintWriter csvOut = ...) {
...
} // Automatic close

关于java - 无法删除或重命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25259007/

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