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

how to assign an existing file object to another file object

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

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?.