package se.kodapan.osm.sweden;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/**
* @author kalle
* @since 2012-03-06 01:18
*/
public class FileUtils {
private static Logger log = LoggerFactory.getLogger(FileUtils.class);
/**
* @param path
* @throws IOException if path not exists and could not be created.
*/
public static File mkdirs(File path) throws IOException {
path = getCleanAbsolutePath(path);
// todo find parents and throw exception if the first existing is not a directory
if (!path.exists()) {
if (!path.mkdirs()) {
throw new IOException("Could not mkdirs " + path.getAbsolutePath());
}
// log.info("Created directory " + path.getAbsolutePath());
}
return path;
}
/**
* Makes "/tmp/a/b/c/./../.." into "/tmp/a/b/c"
*
* @param path
* @return
* @throws IOException
*/
public static File getCleanAbsolutePath(File path) throws IOException {
path = new File(path.getAbsolutePath());
while (path.isDirectory()) {
if (".".equals(path.getName())) {
path = path.getParentFile();
} else if ("..".equals(path.getName())) {
path = path.getParentFile();
} else {
break;
}
}
return path;
}
public static Serializable loadSerializable(File file) throws Exception {
log.info("Loading " + getCleanAbsolutePath(file).getAbsolutePath());
Serializable serializable;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
try {
serializable = (Serializable) ois.readObject();
} finally {
ois.close();
}
return serializable;
}
public static void saveSerializable(Serializable serializable, File file) throws Exception {
log.info("Saving " + getCleanAbsolutePath(file).getAbsolutePath());
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
try {
oos.writeObject(serializable);
} finally {
oos.close();
}
}
}