Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何根据需要生成文件名?_Java - Fatal编程技术网

Java 如何根据需要生成文件名?

Java 如何根据需要生成文件名?,java,Java,有人建议我使用此代码来解决我的一个问题: private static final String PATH_FMT = "C:\\Users\\{0}\\Desktop\\Bloomberg Rechnung-{1,date,yyyyMMdd}{2,choice,0< ({2})}.xlsx"; private File save() throws IOException { Date now = new Date(); for (int fCounter =

有人建议我使用此代码来解决我的一个问题:

private static final String PATH_FMT = 
    "C:\\Users\\{0}\\Desktop\\Bloomberg Rechnung-{1,date,yyyyMMdd}{2,choice,0< ({2})}.xlsx";

private File save() throws IOException {
    Date now = new Date();
    for (int fCounter = 0; ; fCounter++) {
        Path path = Paths.get(
            MessageFormat.format(PATH_FMT, this.username, now, fCounter)
        );
        try (OutputStream out = Files.newOutputStream(path, CREATE_NEW)) {
            this.wb.write(out);
            this.wb.close();
            return path.toFile();
        } catch (FileAlreadyExistsException incrCounterAndRetry) {
        }
    }
}
私有静态最终字符串路径\u FMT=
“C:\\Users\\{0}\\Desktop\\Bloomberg Rechnung-{1,date,yyyyMMdd}{2,choice,0<({2})}.xlsx”;
私有文件save()引发IOException{
现在日期=新日期();
for(int fCounter=0;fCounter++){
Path=Path.get(
MessageFormat.format(PATH_FMT,this.username,now,fCounter)
);
try(OutputStream out=Files.newOutputStream(路径,CREATE\u NEW)){
这个.wb.写(出);
this.wb.close();
返回path.toFile();
}catch(计数器和重试中的FileReadyExistsException){
}
}
}

遗憾的是,这段代码并没有完全满足我的要求。它应该创建一个文件。它应该创建的第一个文件周围没有其他文件名,不应该有计数器。创建的第二个文件应在文件名中包含计数器(无论从何处开始)。我当前获得的第一个文件是计数器为0的文件。有人能帮我解决这个问题吗?也许有人能给我解释一下
{2,choice,0<({2}}}
是如何工作的


提前感谢

请尝试
{2,选择,0 | 0如果
此用户名
是当前用户,您可以使用此设置使路径更具相对性:%userprofile%\\Desktop\\Bloomberg rechnng-{1,date,yyyyymmdd}{2,选择,0<({2}).xlsx我建议您先阅读JavaDocs:已经阅读了文档,但没有帮助我解决它。与您期望的相比,您实际得到了什么?我目前得到了一个带有计数器0的文件。是的,这是我想要的。有没有办法让计数器从0开始?您可以解释一下这到底是做什么的吗?您的意思是什么n通过“计数器从0开始”?我对我的答案添加了更多的解释。我的意思是创建的第一个文件中不应该有计数器。然后创建的第二个文件中应该有一个计数器,它从0开始,而不是从1开始。如果不可能,这没有问题,但我只是好奇它是否可能。您可以从-1开始使用
fCounter
{2,选择,-1#|-1ah是的,太简单了,我自己也没弄明白。非常感谢你解决了我的问题