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

时间:2015-01-23 10:30:19

标签: java file-io

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

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

1 个答案:

答案 0 :(得分:1)

我将如何查看内容,因为您没有打印任何有关文件路径更改,验证等的输出。

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

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

如果您查看File构造函数的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?