commit | author | age
|
e369b9
|
1 |
/* |
c45b52
|
2 |
fm - File management class library |
e369b9
|
3 |
Copyright (C) 2024 Ulrich Hilger |
U |
4 |
|
|
5 |
This program is free software: you can redistribute it and/or modify |
|
6 |
it under the terms of the GNU Affero General Public License as |
|
7 |
published by the Free Software Foundation, either version 3 of the |
|
8 |
License, or (at your option) any later version. |
|
9 |
|
|
10 |
This program is distributed in the hope that it will be useful, |
|
11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
13 |
GNU Affero General Public License for more details. |
|
14 |
|
|
15 |
You should have received a copy of the GNU Affero General Public License |
|
16 |
along with this program. If not, see <https://www.gnu.org/licenses/>. |
|
17 |
*/ |
|
18 |
package de.uhilger.fm; |
|
19 |
|
|
20 |
import java.io.File; |
|
21 |
|
|
22 |
/** |
|
23 |
* FileHelper |
|
24 |
* |
|
25 |
* @author Ulrich Hilger |
|
26 |
* @version 1, 04.07.2021 |
|
27 |
*/ |
|
28 |
public class FileHelper { |
|
29 |
|
|
30 |
/** |
|
31 |
* Einen Namen fuer eine Datei erzeugen, der noch nicht existiert. |
|
32 |
* |
|
33 |
* Der Dateiname wird wie folgt gebildet |
|
34 |
* '[Bestehender Dateiname]-[Nummer].[Erweiterung]' |
|
35 |
* |
|
36 |
* Ordner haben in der Regel keine Erweiterung, dann lautet der neue Name |
|
37 |
* '[Bestehender Ordnername]-[Nummer]' |
|
38 |
* |
|
39 |
* Fuer Nummer wird eine Nummer mit 1 beginnend heraufgezaehlt bis ein |
|
40 |
* Dateiname entsteht, den es im betreffenden Ordner noch nicht gibt. |
|
41 |
* |
|
42 |
* @param file die Datei, die schon existiert |
|
43 |
* @return ein Dateiname, der im Ordner noch nicht verwendet wird |
|
44 |
*/ |
|
45 |
public File getNewFileName(File file) { |
|
46 |
File dir = file.getParentFile(); |
|
47 |
String targetName = file.getName(); |
|
48 |
//logger.fine("targetName: " + targetName); |
|
49 |
String ext = ""; |
|
50 |
int dotpos = targetName.indexOf("."); |
|
51 |
if (dotpos > -1) { |
|
52 |
ext = targetName.substring(dotpos); |
|
53 |
targetName = targetName.substring(0, dotpos); |
|
54 |
} |
|
55 |
//logger.fine("targetName: " + targetName + ", ext: " + ext); |
|
56 |
int i = 1; |
|
57 |
while (file.exists()) { |
|
58 |
StringBuilder buf = new StringBuilder(); |
|
59 |
buf.append(targetName); |
|
60 |
buf.append("-"); |
|
61 |
buf.append(i); |
|
62 |
if (ext.length() > 0) { |
|
63 |
buf.append(ext); |
|
64 |
} |
|
65 |
file = new File(dir, buf.toString()); |
|
66 |
i++; |
|
67 |
} |
|
68 |
//logger.fine("new file: " + file.getName()); |
|
69 |
return file; |
|
70 |
} |
|
71 |
|
|
72 |
} |