|
1 | 1 | package org.jabref.logic.util.io;
|
2 | 2 |
|
| 3 | +import java.nio.file.Files; |
| 4 | +import java.nio.file.Path; |
| 5 | +import java.nio.file.Paths; |
3 | 6 | import java.util.Arrays;
|
| 7 | +import java.util.Optional; |
4 | 8 |
|
5 | 9 | /**
|
6 | 10 | * This class is based on http://stackoverflow.com/a/5626340/873282
|
@@ -67,6 +71,38 @@ public static String cleanDirectoryName(String badFileName) {
|
67 | 71 | return cleanName.toString().trim();
|
68 | 72 | }
|
69 | 73 |
|
| 74 | + /** |
| 75 | + * Returns an absolute path to a file which does not match with any existing file names |
| 76 | + * |
| 77 | + * @param targetDirectory The directory in which file name should be unique |
| 78 | + * @param fileName Suggested name for the file |
| 79 | + * @return a file-name such that it does not match any existing files in targetDirectory. |
| 80 | + * */ |
| 81 | + public static String getNonOverWritingFileName(Path targetDirectory, String fileName) { |
| 82 | + String absoluteName = targetDirectory.resolve(fileName) |
| 83 | + .toString(); |
| 84 | + |
| 85 | + Optional<String> extensionOptional = FileUtil.getFileExtension(fileName); |
| 86 | + |
| 87 | + // the suffix include the '.' , if extension is present Eg: ".pdf" |
| 88 | + String extensionSuffix = ""; |
| 89 | + String fileNameWithoutExtension = fileName; |
| 90 | + |
| 91 | + if(extensionOptional.isPresent()) { |
| 92 | + extensionSuffix = '.'+extensionOptional.get(); |
| 93 | + fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.')); |
| 94 | + } |
| 95 | + |
| 96 | + Path absolutePath = Paths.get(absoluteName); |
| 97 | + String newFileName = fileName; |
| 98 | + |
| 99 | + for(int counter = 1; Files.exists(absolutePath); ++counter) { |
| 100 | + newFileName = fileNameWithoutExtension+" ("+counter+")"+extensionSuffix; |
| 101 | + absolutePath = targetDirectory.resolve(newFileName); |
| 102 | + } |
| 103 | + return newFileName; |
| 104 | + } |
| 105 | + |
70 | 106 | private static boolean isCharLegal(char c) {
|
71 | 107 | return Arrays.binarySearch(FileNameHandler.ILLEGAL_CHARS, c) < 0;
|
72 | 108 | }
|
|
0 commit comments