0

我正在从 Soap UI 运行用 Groovy 制作的脚本,该脚本需要生成大量文件。这些文件的名称还包含列表中的两个数字(该列表中的所有组合都是不同的),并且有 1303 个组合可用,脚本仅生成 1235 个文件。

代码的一部分是:

filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();

其中 $file 实际上是文件名的一部分,其中包括该列表中的这两种组合:

file = "abc" + "-$firstNumer"+"_$secondNumber"

对于那些未创建的文件,返回一条消息:“文件名、目录名或卷标语法不正确”。

我试过放另一条路:

filename = "D:\\rez\\" + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile(); 

并且:

File parentFolder = new File("D:\\rez\\");
File targetFile = new File(parentFolder, "$file"+"_OK.txt");
targetFile.createNewFile();

(我在这里找到:Java.io.IOException 的可能原因是什么:“文件名、目录名或卷标语法不正确”)但没有任何效果。

我不知道问题出在哪里。奇怪的是 1235 个文件创建好了,其余的 68 个根本没有创建。

谢谢,

4

2 回答 2

1

File.createNewFile()false当具有该名称的文件或目录已经存在时返回。在所有其他故障情况(安全性、I/O)中,它都会引发异常。

EvaluatecreateNewFile()的返回值,或者,另外,使用File.exists()方法:

File file = new File("foo")
// works the first time
createNewFile(file)
// prints an error message
createNewFile(file)

void createNewFile(File file) {
    if (!file.createNewFile()) {
        assert file.exists()
        println file.getPath() + " already exists."
    }
}
于 2010-10-28T17:39:44.827 回答
1

我的猜测是某些文件的路径中有非法字符。究竟哪些字符是非法的是特定于平台的,例如在 Windows 上它们是

\ / : * ? " < > |

为什么不记录targetFile.createNewFile();调用之前文件的完整路径并记录此方法是否成功,例如

filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
println "attempting to create file: $targetFile"

if (targetFile.createNewFile()) {
    println "Successfully created file $targetFile"
} else {
    println "Failed to create file $targetFile"
}

该过程完成后,检查日志,我怀疑您会在“创建文件失败......”消息中看到一个常见模式

于 2010-10-28T15:59:36.023 回答