При создании нового файла, вы должны проверить, если файл с таким fileNumber
или index
уже существует. Пока существует файл с таким index
, то index
должен быть увеличен. Наконец, вы создаете новый файл с index
, который не существует.
Скажем, вы создали абстрактное представление файла и теперь хотите переименовать его в первый доступный index
. Давайте предположим, что другие файлы расположены на C:\tmp
:
File newFile;
int index = 1;
String parent = "C:\\tmp"
String name = "Person";
while ((newFile = new File(parent, name + index)).exists()) {
index++;
}
/* Here you have a newFile with name set to the first available index */
Или, если вы хотите, чтобы рассмотреть возможность расширения:
File newFile;
int index = 1;
String parent = "C:\\tmp"
String name = "Person";
String extension = ".txt";
while ((newFile = new File(parent, name + index + extension)).exists()) {
index++;
}
/* Here you have a newFile with name set to the first available index and extension */
UPDATE: Использование Java 8 NIO API, я создал следующие способ вернуть Path
объект для первого доступного пути, который еще не существует в файловой системе:
/**
* Returns the first available {@code Path} with a unique file name. The
* first available path means that, if a file with the specified
* <tt>path</tt> exists on disk, an index is appended to it. If a file with
* that path still exists, index is incremented and so on, until a unique
* path is generated. This path is then returned.
* <p>
* If a file with the specified <tt>path</tt> does not exist, this method
* trivially returns <tt>path</tt>.
* <p>
* For an example, if the parent directory of the specified path already
* contains <tt>file.txt</tt>, <tt>file-0.txt</tt> and <tt>file-1.txt</tt>,
* and the file name of this path is <tt>file.txt</tt>, then a path with
* file name <tt>file-2.txt</tt> is returned.
*
* @param path path from which the first available is returned
* @return a path with a unique file name
*/
public static Path firstAvailable(Path path) {
if (!Files.exists(path))
return path;
int namingIndex = 0;
String name = path.getFileName().toString();
String extension = "";
int dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
extension = name.substring(dotIndex);
name = name.substring(0, dotIndex);
}
name += "-";
while (Files.exists(path)) {
path = path.resolveSibling(name + namingIndex + extension);
namingIndex++;
}
return path;
}
* Следующий код времени выполняется, текстовый файл должен называться Person2 * Вы имеете в виду следующий раз, когда программа запущена? – user2004685
Нет, код может выполняться несколько раз разными пользователями. 1 пользователь может создавать несколько текстовых файлов, но текстовым файлам нужны разные имена. – AnotherUser
Пожалуйста, поставьте «e.printStackTrace()» в блок catch и добавьте результат в вопрос. При этом вы, вероятно, сможете самостоятельно диагностировать проблему. – Dale