日期:2014-05-17 浏览次数:20887 次
public static String getTempDirectoryPath() {
return System.getProperty("java.io.tmpdir");
}public static File getTempDirectory() {
return new File(getTempDirectoryPath());
}public static String getUserDirectoryPath() {
return System.getProperty("user.home");
}public static File getUserDirectory() {
return new File(getUserDirectoryPath());
}public static FileOutputStream openOutputStream(File file) throws IOException {
return openOutputStream(file, false);
}public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canWrite() == false) {
throw new IOException("File '" + file + "' cannot be written to");
}
} else {
File parent = file.getParentFile();
if (parent != null) {
if (!parent.mkdirs() && !parent.isDirectory()) {
throw new IOException("Directory '" + parent + "' could not be created");
}
}
}
return new FileOutputStream(file, append);
}/**
* The number of bytes in a kilobyte.
*/
public static final long ONE_KB = 1024;
/**
* The number of bytes in a megabyte.
*/
public static final long ONE_MB = ONE_KB * ONE_KB;
/**
* The number of bytes in a gigabyte.
*/
public static final long ONE_GB = ONE_KB * ONE_MB;
public static String byteCountToDisplaySize(long size) {
String displaySize;
// if (size / ONE_EB > 0) {
// displaySize = String.valueOf(size / ONE_EB) + " EB";
// } else if (size / ONE_PB > 0) {
// displaySize = String.valueOf(size / ONE_PB) + " PB";
// } else if (size / ONE_TB > 0) {
// displaySize = String.valueOf(size / ONE_TB) + " TB";
// } else
if (size / ONE_GB > 0) {
displaySize = String.valueOf(size / ONE_GB) + " GB";
} else if (size / ONE_MB > 0) {
displaySize = String.valueOf(size / ONE_MB) + " MB";
} else if (size / ONE_KB > 0) {
displaySize = String.valueOf(size / ONE_KB) + " KB";
} else {
displaySize = String.valueOf(size) + " bytes";
}
return displaySize;
}public static void touch(File file) throws IOException {
if (!file.exists()) {
OutputStream out = openOutputStream(file);
IOUtils.closeQuietly(out);
}
boolean success = file.setLastModified(System.currentTimeMillis());
if (!success) {
throw new IOException("Unable to set the last modification time for " + file);
}
}
public static void closeQuietly(OutputStream output) {
closeQuietly((Closeable)output);
}
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ioe) {
// ignore
}
}