package T1_File;
import java.io.*;
public class FileUtils {
private static File absoluteFile(String path) {
File file = new File(path);
file = file.getAbsoluteFile();
return file;
}
public static boolean move(String src, String dest) {
boolean copyResult = copy(src, dest);
boolean removeResult = remove(src);
return (copyResult && removeResult);
}
public static boolean copy(String src, String dest) {
File source = absoluteFile(src);
File target = absoluteFile(dest);
// 如果目标目录存在,则直接将源文件夹拷贝到目标文件夹中
if (target.exists() && target.isDirectory()) {
target = new File(target, source.getName());
}
try {
folderCopy(source, target);
} catch (IOException e) {
return false;
}
return true;
}
private static void folderCopy(File source, File target) throws IOException {
if (!source.exists()) {
return;
}
if (source.isFile()) {
fileCopy(source, target);
return;
}
if (source.isDirectory()) {
boolean created = target.exists() || target.mkdirs();
File[] files = source.listFiles();
if (files != null && created) {
for (File fs : files) {
File ft = new File(target, fs.getName());
folderCopy(fs, ft);
}
}
}
}
private static void fileCopy(File source, File target) throws IOException {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target);
byte[] bytes = new byte[1024 * 1024];
int length = 0;
while (length != -1) {
fos.write(bytes, 0, length);
length = fis.read(bytes);
}
fis.close();
fos.close();
}
public static String info(String path) {
File file = absoluteFile(path);
long size = countTotalBytes(file);
String info = humanReadable(size);
return String.format("%s (%,d 字节)", info, size);
}
private static String humanReadable(long size) {
String info = size + " B";
if (1024L <= size) {
info = String.format("%.2f KB", size / 1024.0);
}
if (1048576L <= size) {
info = String.format("%.2f MB", size / 1048576.0);
}
if (1073741824L <= size) {
info = String.format("%.2f GB", size / 1073741824.0);
}
return info;
}
public static long size(String path) {
File file = absoluteFile(path);
return countTotalBytes(file);
}
private static long countTotalBytes(File file) {
if (!file.exists()) {
return -1L;
}
if (file.isFile()) {
return file.length();
}
if (file.isDirectory()) {
long sumSize = 0L;
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
sumSize += countTotalBytes(f);
}
}
return sumSize;
}
return 0L;
}
public static boolean remove(String path) {
File file = absoluteFile(path);
return deleteAllFiles(file);
}
private static boolean deleteAllFiles(File file) {
if (!file.exists()) {
return false;
}
if (file.isFile()) { // 若是文件
return file.delete(); // 直接删除
}
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) { // 遍历目录
if (!deleteAllFiles(f)) { // 递归删除
return false;
}
}
}
return file.delete(); // 删除空文件夹
}
return false;
}
}