Java:renameTo()函数失败

时间:2011-07-05 20:10:53

标签: java

爪哇

下面的代码是为了读取所有文件而编写的,并将数据发送到另一个方法(setOutput()),然后调用一个方法将最后一个读取文件重命名为另一个目录,然后删除原始文件。在调用smdrCleanup()方法之前,一切似乎都有效。 renameTo()失败。

根据我的理解,如果FileReader包装在BufferedReader中,我只需要调用BufferedReader.close()来释放最后一个读取文件......我在这里做。

我还看到,如果文件仍处于“打开”状态,被防病毒程序扫描,或者被进程锁定,则renameTo()函数将失败。我已经使用Process Explorer查看可能锁定它的内容,但我没有看到任何锁定它。

我的方法设置为抛出任何类型的IOExceptions,但我没有得到任何异常。一切都在运行,但控制台只是说文件没有被复制。

我正在运行Eclipse Helios Release 2,Windows 7旗舰版,本地管理员,UAC已禁用。

非常感谢任何帮助。

public void smdrReader(String path, String oldPath) throws IOException
{
  output = null; //nullify the value of output to avoid duplicate data
  File folder = new File(path); //setting the directory for raw data files
  File[] listOfFiles = folder.listFiles(); //array of files within the folder/directory

  //For loop to iterate through the available files, open, & read contents to String Buffer.
  for (int i = 0; i < listOfFiles.length; i++) 
  {

      if (listOfFiles[i].isFile()) //verifying next entry in array is a file
      {
          File fileName = new File(listOfFiles[i].getName());//getting file name from array iteration
          StringBuffer fileData = new StringBuffer(2048);//establishing StringBuffer for reading file contents into
          BufferedReader reader = new BufferedReader(new FileReader(path + fileName));//reader to actually access/read file
          String readData = String.valueOf(reader);//String variable being set to value of the reader
          fileData.append(readData);//appending data from String variable into StringBuffer variable
          setOutput(fileData);//setting the value of "output" to the value of StringBuffer
          fileData.delete(0, i);
          reader.close();//closing the reader (closing the file)
          smdrCleanup(oldPath,fileName.toString());//calling method to move processed file and delete original
      }

  }

}

//method to rename input file into another directory and delete the original file to avoid duplicate processing
public void smdrCleanup(String oldPathPassed, String fileNamePassed) throws IOException   
{
   File oldFile = new File(oldPathPassed);//establishing File object for path to processed folder
   File fileName = new File(fileNamePassed);//establishing File object for the fileName to rename/delete
   String oldFilePath = oldFile.toString();
   boolean success = fileName.renameTo(new File(oldFilePath + "\\" + fileName + ".old"));//attempting to rename file
    if (!success) //checking the success of the file rename operation
    {
        System.out.println("The File Was NOT Successfully Moved!");//reporting error if the file cannot be renamed
    }
        else
        {
            fileName.delete();//deleting the file if it was successfully renamed
        }
}

2 个答案:

答案 0 :(得分:1)

oldFile.toString();会返回文件的完整路径,包括其文件名,因此,如果您的旧文件路径为 c:\ path \ to \ file.txt oldFilePath + "\\" + fileName + ".old" c:\ path \ to \ file.txt \ file.txt.old

由于没有文件夹 c:\ path \ to \ file.txt ,因此失败。将其更改为

boolean success = fileName.renameTo(new File(oldFilePath + ".old"));

你应该好好去。

答案 1 :(得分:1)

File.renameTo可能由于多种原因而失败:

  

这种行为的许多方面   方法本质上   依赖于平台:重命名   操作可能无法移动   从一个文件系统到另一个文件系统,   它可能不是原子的,它可能   如果一个文件与。不成功   目的地抽象路径名已经   存在。返回值应始终   检查以确保   重命名操作成功。

但对于它失败的原因并没有多少反馈。在调用renameTo之前,请验证您正在移动的文件是否存在,以及您要将其移动到的父目录是否存在,以及canWrite()。这些是否在同一磁盘卷上?如果没有,它可能会失败。

* 编辑:添加了代码示例*

尝试以下内容。修改:

  1. 接受文件对象而不是字符串
  2. 使用2-arg File构造函数在父目录中创建子File对象
  3. 更好的错误检查
  4. 这可能会为你提供一些失败的线索。

    public void smdrCleanup(File oldPathPassed, File fileNamePassed) throws IOException {
        if (!oldPathPassed.exists() || !oldPathPassed.isDirectory() || !oldPathPassed.canWrite() ) throw new IOException("Dest is not a writable directory: " + oldPathPassed);
        if (!fileNamePassed.exists()) throw new IOException("File does not exist: " + fileNamePassed);
        final File dest = new File(oldPathPassed, fileNamePassed + ".old");
        if (dest.exists()) throw new IOException("File already exists: " + dest);
        boolean success = (fileNamePassed).renameTo(dest);//attempting to rename file
        if (!success) //checking the success of the file rename operation
        {
            throw new IOException("The File Was NOT Successfully Moved!");
        } else {
            // file was successfully renamed, no need to delete
        }
    }