gpt4 book ai didi

java - 如何将现有文件对象分配给另一个文件对象

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

我需要重命名没有扩展名的文件,然后我需要传递重命名的文件(带扩展名)。但是重命名后,当我将该对象分配给新文件对象时,我仍然得到旧文件对象(没有扩展名的文件),请参阅下面的代码

srcFileName = tempFile.getName();

file = new File(uploadDir + srcFileName);

indexF = srcFileName.lastIndexOf(".xml");

extFile = srcFileName.substring(indexF + 1, indexF + 4);

if (!extFile.equalsIgnoreCase("zip"))
{
if (indexF == -1)
{
extFile = "xml";
srcFileName = srcFileName + "." + extFile;
boolean rename = file.renameTo(new File(uploadDir + srcFileName));

File renamedFile = new File(uploadDir + srcFileName);
indexF = srcFileName.lastIndexOf(".xml");
extFile = srcFileName.substring(indexF + 1, indexF + 4);
long len = 0;
len = renamedFile.length();
debug("renamed file Length::" + len);
//tempFile=renamedFile;

allDetailsMap.put("listOfFiles", renamedFile);
}
}

最佳答案

我将按照我的检查方式进行,因为您尚未打印任何有关文件路径更改、验证等的输出。

假设您的重命名操作成功,即 boolean rename 计算为 true,我们的文件构造函数应该是:

 File renamedFile = new File(file, (uploadDir + srcFileName));

如果您查看 JDK 文档中的文件构造函数:

    public File(File parent,
String child)

Creates a new File instance from a parent abstract pathname and a child pathname string.

If parent is null then the new File instance is created as if by invoking the single-argument File constructor on the given child pathname string.

Otherwise the parent abstract pathname is taken to denote a directory, and the child pathname string is taken to denote either a directory or a file. If the child pathname string is absolute then it is converted into a relative pathname in a system-dependent way. If parent is the empty abstract pathname then the new File instance is created by converting child into an abstract pathname and resolving the result against a system-dependent default directory. Otherwise each pathname string is converted into an abstract pathname and the child abstract pathname is resolved against the parent.

Parameters:
parent - The parent abstract pathname
child - The child pathname string

另外,摘录自 renameTo 区域(我确定您已经完成了此操作):

The return value should always be checked to make sure that the rename operation was successful. 

此外,您必须使用 getAbsolutePath() 来确认您的文件已重命名,以查看最后一位是否包含扩展名。一个很好的例子在这里 - What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java? .

关于java - 如何将现有文件对象分配给另一个文件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107858/

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