mihon/app/src/main/java/eu/kanade/tachiyomi/util/DiskUtils.java

101 lines
2.8 KiB
Java
Raw Normal View History

2016-01-15 09:18:19 -05:00
package eu.kanade.tachiyomi.util;
2015-10-05 18:24:29 -04:00
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
public final class DiskUtils {
private DiskUtils() {
throw new AssertionError();
}
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
2015-11-03 10:21:50 -05:00
public static File saveBufferedSourceToDirectory(BufferedSource bufferedSource, File directory, String name) throws IOException {
createDirectory(directory);
2015-10-05 18:24:29 -04:00
2015-11-03 10:21:50 -05:00
File writeFile = new File(directory, name);
2015-10-05 18:24:29 -04:00
if (writeFile.exists()) {
if (writeFile.delete()) {
2015-11-03 10:21:50 -05:00
writeFile = new File(directory, name);
2015-10-05 18:24:29 -04:00
} else {
throw new IOException("Failed Deleting Existing File for Overwrite");
}
}
BufferedSink bufferedSink = null;
try {
bufferedSink = Okio.buffer(Okio.sink(writeFile));
bufferedSink.writeAll(bufferedSource);
} catch (Exception e) {
writeFile.delete();
throw new IOException("Unable to save image");
} finally {
2015-10-05 18:24:29 -04:00
if (bufferedSink != null) {
bufferedSink.close();
}
}
return writeFile;
}
public static void deleteFiles(File inputFile) {
if (inputFile.isDirectory()) {
for (File childFile : inputFile.listFiles()) {
deleteFiles(childFile);
}
}
inputFile.delete();
}
public static synchronized void createDirectory(File directory) throws IOException {
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Failed creating directory");
}
}
public static long getDirectorySize(File f) {
long size = 0;
if (f.isDirectory()) {
for (File file : f.listFiles()) {
size += getDirectorySize(file);
}
} else {
size=f.length();
}
return size;
}
2015-10-05 18:24:29 -04:00
}