b9f766e658c4fadf1a8bef97b0c71afad7a337bb
[jalview.git] / src / jalview / io / BackupFilenameParts.java
1 package jalview.io;
2
3 import java.io.File;
4
5 public class BackupFilenameParts
6 {
7   String base;
8
9   String templateStart;
10
11   int num;
12
13   int digits;
14
15   String templateEnd;
16
17   String extension;
18
19   boolean isBackupFile;
20
21   public BackupFilenameParts(File file, String base, String template, int digits,
22           String extension)
23   {
24     this(file.getName(), base, template, digits, extension);
25   }
26
27   public BackupFilenameParts(String filename, String base, String template,
28           int digits, String extension)
29   {
30     this.isBackupFile = false;
31
32     // calculate minimum length of a backup filename
33     int minlength = base.length() + template.length()
34             - BackupFiles.NUM_PLACEHOLDER.length() + digits
35             + extension.length();
36
37     if (!(filename.startsWith(base) && filename.endsWith(extension)
38             && filename.length() >= minlength))
39     {
40       // non-starter
41       return;
42     }
43
44     int numcharstart = template.indexOf(BackupFiles.NUM_PLACEHOLDER);
45     String templateStart = template;
46     String templateEnd = "";
47     if (numcharstart > -1)
48     {
49       templateStart = template.substring(0, numcharstart);
50       templateEnd = template.substring(
51               numcharstart + BackupFiles.NUM_PLACEHOLDER.length());
52     }
53     
54     int startLength = base.length() + templateStart.length();
55     int endLength = templateEnd.length() + extension.length();
56     String numString = filename.substring(startLength,
57             filename.length() - endLength);
58
59     if (filename.length() >= startLength + digits + endLength
60             && filename.startsWith(base + templateStart)
61             && filename.endsWith(templateEnd + extension)
62             && numString.matches("[0-9]+"))
63     {
64       this.base = base;
65       this.templateStart = templateStart;
66       this.num = Integer.parseInt(numString);
67       this.digits = digits;
68       this.templateStart = templateStart;
69       this.templateEnd = templateEnd;
70       this.isBackupFile = true;
71     }
72     
73   }
74
75   public boolean isBackupFile()
76   {
77     return this.isBackupFile;
78   }
79
80   public int indexNum()
81   {
82     return this.num;
83   }
84 }