在Groovy(Windows)中读取文件时,我遇到了一个非常令人沮丧的问题。我花了很多时间试图找出根本原因。但是,我将其简化为两个不匹配的相同文件名,所以我很困惑!

这是一些诊断代码和结果:

def rootPath = "x:/"
def filePath

files.each
{

    filePath = rootPath + it
    File xmlFile = new File(filePath)
    println xmlFile.canRead()    //returns : false
    println xmlFile.exists()     //returns : false

    xmlFile = new File(new File(filePath).getParent() + "/" + new File(filePath).getName().toString())
    println xmlFile.canRead()     //returns : false


    String fileName = new File(filePath).getName()
    String parentDir = new File(filePath).getParent()
    new File(parentDir).list().each
    {
        println "|" + it + "|" + fileName + "|"
               //returns |PreUpload_140111-192158.xml|PreUpload_140111-192158.xml|

        println it.toString().equals(fileName)
               //returns false!!

        println "Can Read : " + new File(parentDir + "/" + it.toString()).canRead()
               //returns true
    }
}

最佳答案

通过此清理代码,您得到相同的结果吗?

def rootPath = "x:/"

files.each { f ->
  File xmlFile = new File( rootPath, f )
  String filename = xmlFile.name
  File parentDir = xmlFile.parent

  parentDir.list().each { f2 ->
    // Does this still print |PreUpload_140111-192158.xml|PreUpload_140111-192158.xml|
    println "|$f2|$fileName|"

    // Does this still print false?
    println( f2 == fileName )

    boolean canRead = new File( parentDir, f2 ).canRead()

    // still prints true ?
    println "Can Read : $canRead"
  }
}




[编辑]

因此,问题似乎出在CR集合中字符串末尾的files个字符

不确定变量files的填充方式,但是某些地方需要trim() ;-)

关于java - 文件存在,无法以标准方式读取给出的路径,相同的字符串不匹配-Groovy,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4957785/

10-09 07:00
查看更多