如何在程序执行期间更改文件名

时间:2015-04-22 14:30:13

标签: java file

我必须运行一些模拟,输出应该在文件中,输出的数量可以从模拟更改为另一个,例如,第一个模拟我使用10个文件,第二个将是14个文件。让我们说我有N个文件

我使用以下指令声明N个文件:

String path1="C:/Users/Desktop/path1.txt";
File file1 =new File(path1);

写入文件1我使用此功能:

write(my outputs list,path1,file1);

在执行期间,根据一些参数,我选择要在其上写入的文件,我想在不使用switch case指令的情况下执行此选项,因为如果编号不容易管理它文件很大。

使用switch case就像是:

int choice1 = number;
switch (choice1) {
case 1 :        
write(outputs ,path1,file1);
break;
case 2 :        
    write(outputs ,path2,file2);
break;
case 3 :
.......
}

我想用其他指令替换开关盒

例如,为了改变路径,我使用了:

String path= "path"+number;

其中number是要在其上写入的路径文件的编号。 然后我可以调用我的函数write(outputs, path, file),但是 我想对文件做同样的事情,但我不知道如何。 请帮忙。

2 个答案:

答案 0 :(得分:0)

你可以使用'file.renameTo(someOtherFile)`。这可能很重要:Reliable File.renameTo() alternative on Windows?

答案 1 :(得分:0)

路径包含文件名,因此在您的路径String中包含文件名另一个示例,如果您要在应用结构中编写文件:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("folder" + number + "/filename" + number + ".xml").getFile());