2 * DemosceneMusic - DataDirectory.java - Copyright © 2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.demoscenemusic.core;
23 * Helper for managing the data directory.
25 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
27 public class DataDirectory {
29 /** The path of the data directory. */
30 private final String dataDirectory;
33 * Creates a new data directory helper.
35 * @param dataDirectory
36 * The path of the data directory
38 public DataDirectory(String dataDirectory) {
39 this.dataDirectory = dataDirectory;
43 * Returns the absolute path of the file with the given ID.
47 * @return The absolute path of the file
49 public String getPath(String id) {
50 return new File(new File(dataDirectory, getDirectoryName(id)), getFileName(id)).getAbsolutePath();
54 * Returns the file for the given ID. The returned {@link File} is ready to
55 * be read from or written to, all necessary directories have been created.
61 public File getFile(String id) {
62 File file = new File(dataDirectory, getDirectoryName(id));
64 return new File(file, getFileName(id));
68 * Removes the file and all its directories, up to the
69 * {@link #dataDirectory}.
72 * The ID of the file to remove
74 public void removeFile(String id) {
75 File file = getFile(id);
77 File parentDirectory = file.getParentFile();
78 String lastDirectory = new File(dataDirectory).getAbsolutePath();
79 while (!lastDirectory.equals(parentDirectory.getAbsolutePath()) && (parentDirectory.listFiles().length == 0)) {
80 parentDirectory.delete();
81 parentDirectory = parentDirectory.getParentFile();
91 * Returns the relative name of the directory that the file for the given ID
95 * The ID of the file to store
96 * @return The name of the directory to store the file in
98 private String getDirectoryName(String id) {
99 String realId = id.replaceAll("-", "").toLowerCase();
100 return realId.substring(0, 2) + "/" + realId.substring(2, 4) + "/" + realId.substring(4, 6) + "/" + realId.substring(6, 8);
104 * Returns the name of the file for the given ID, relative to its
105 * {@link #getDirectoryName(String) directory}.
108 * The ID of the file to store
109 * @return The name of the file to store the file in
111 private String getFileName(String id) {
112 String realId = id.replaceAll("-", "").toLowerCase();
113 return realId.substring(8);