/**
* 檔案重新命名
* @param fromPath 檔案所在目錄
* @param suffix 目標檔案的字尾格式
*/
public static void reName(String fromPath,String suffix) {
File file = new File(fromPath);
// 判斷是不是檔案目錄
if (file.isDirectory()) {
//獲取目錄下所有檔案
File[] files = file.listFiles();
int number = 0;
//遍歷目錄下的檔案
for (File fileFrom : files) {
number++;
String fromFileName = fileFrom.getName();
String toFileName = fromPath + File.separator + number + "."+suffix;
File toFile = new File(toFileName);
// 開始更名
fileFrom.renameTo(toFile);
System.out.println(fromFileName+"---成功重新命名為---"+number + "."+suffix);
}
}
}
/**
* 獲得單個檔案的大小(KB)
* @param path 檔案的路徑
*/
public static float getSingleFileSize(String path) throws IOException {
FileInputStream fis = null;
File f = new File(path);
float size = 0;
try {
if (f.exists()) {
if (f.isDirectory()) {
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
size = size + getSingleFileSize(flist[i].getPath());
}
} else {
fis = new FileInputStream(f);
size = fis.available();
size = (float) (size / 1024);
}
} else {
f.createNewFile();
System.out.println("檔案不存在");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fis.close();
}
return size;
}
/**
* 遍歷目錄下所有檔案的大小(KB)
* @param path 目錄路徑
*/
public static void getPathFileSize(String filePath) throws IOException {
File file = new File(filePath);
if (file.isDirectory()) {
File[] files = file.listFiles();// 獲取此目錄下的檔案列表
for (File fileFrom : files) {
String fileName = fileFrom.getName();
String srcImageFile = fileFrom.getAbsolutePath();
float fileSize = getSingleFileSize(srcImageFile);
System.out.println(fileName + "----size=" + fileSize + "kb");
}
}
}
/**
* 複製單個檔案(原名複製)
* @param oldPathFile 準備複製的檔案源
* @param newPathFile 拷貝到新絕對路徑帶檔名(注:目錄路徑需帶檔名)
* @return
*/
public static void CopySingleFileTo(String oldPathFile, String targetPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPathFile);
String targetfile = targetPath + File.separator + oldfile.getName();
if (oldfile.exists()) { //檔案存在時
InputStream inStream = new FileInputStream(oldPathFile); //讀入原檔案
FileOutputStream fs = new FileOutputStream(targetfile);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //位元組數 檔案大小
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}