大家好,我目前正在用Java编写一个方法,我正在尝试创建新文件,但我需要这些文件不是同名,而是增加名称值,如下所示:
所以我尝试在我的代码中执行以下操作,但是我不明白为什么当我在每个循环中调用该文件时(为了创建一个新的),数字不会增加?
public void pickFolder() throws Exception {
chooserFolder.setDialogTitle("Specify your save location");
chooserFolder.setDialogType(JFileChooser.SAVE_DIALOG);
int numbers = 0;
chooserFolder.setSelectedFile(new File("myFile" + numbers++ + ".xml"));
chooserFolder.setFileFilter(new FileNameExtensionFilter("xml file", "xml"));
int userSelection = chooserFolder.showSaveDialog(null);
if (userSelection == JFileChooser.APPROVE_OPTION) {
for (File file : files) {
chooserFolder.setSelectedFile(new File(chooserFolder.getSelectedFile().getAbsolutePath()));
fileToSave = chooserFolder.getSelectedFile();
if (fileToSave.createNewFile()) {
System.out.println("File is created!");
fileToSave = chooserFolder.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "File already exists.");
}
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
非常感谢任何帮助,谢谢!
答案 0 :(得分:2)
您的数字变量应该是静态的;
public static int numbers = 0;
public void pickFolder() throws Exception {
chooserFolder.setDialogTitle("Specify your save location");
chooserFolder.setDialogType(JFileChooser.SAVE_DIALOG);
chooserFolder.setSelectedFile(new File("myFile" + numbers++ + ".xml"));
chooserFolder.setFileFilter(new FileNameExtensionFilter("xml file", "xml"));
int userSelection = chooserFolder.showSaveDialog(null);
if (userSelection == JFileChooser.APPROVE_OPTION) {
for (File file : files) {
chooserFolder.setSelectedFile(new File(chooserFolder.getSelectedFile().getAbsolutePath()));
fileToSave = chooserFolder.getSelectedFile();
if (fileToSave.createNewFile()) {
System.out.println("File is created!");
fileToSave = chooserFolder.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "File already exists.");
}
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
无论何时调用pickFolder() - 无论是创建新实例还是使用相同的实例 - 您的numbers变量对于每个实例都保持不变。
答案 1 :(得分:1)
那将是因为你将它附加到一个字符串"某些东西" + 1将是java中的字符串连接。
尝试这样的事情:
chooserFolder.setSelectedFile(new File("myFile" + (numbers++) + ".xml"));
这将确保数字递增,然后替换为相应的值。