Java建立、重新命名、刪除檔案和資料夾
阿新 • • 發佈:2018-11-25
- package my.file;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.OutputStreamWriter;
- import java.io.Writer;
- public class TravelAllFile {
- public
- String path = "E:/資料夾";
- File f = new File(path);
- if (f.isDirectory()) {
- new TravelAllFile().getFileName(f);
- }
- delFolder("E:/資料夾");
- System.out.println("deleted");
- }
- // 遞迴查詢函式,引數為file物件
- public void getFileName(File f) {
- // File 陣列
- File[] files = f.listFiles();
- for (int i = 0; i < files.length; i++) {
- // 遞迴出子目錄
- if (files[i].isDirectory()) {
- System.out.println("子目錄是:" + files[i].getName());
- getFileName(files[i]);
- // 遞迴出子檔案
- } else {
- System.out.println(files[i].getName());
- }
- }
- }
- //重新命名
- public void rename(){
- File fl=new File("E://資料夾"); // 這裡寫上發替換的資料夾路徑,注意使用雙斜槓
- String[] files=fl.list();
- File f=null;
- String filename="";
- for(String file:files)
- {
- f=new File(fl,file);// 注意,這裡一定要寫成File(fl,file)如果寫成File(file)是行不通的,一定要全路徑
- filename=f.getName();
- // System.out.println(filename);
- f.renameTo(new File(fl.getAbsolutePath()+"//"+filename.replace("要替換掉的內容", "替換成的內容")));// 這裡可以反覆使用replace替換,當然也可以使用正則表示式來替換了
- }
- }
- //刪除資料夾
- //param folderPath 資料夾完整絕對路徑
- public static void delFolder(String folderPath) {
- try {
- delAllFile(folderPath); //刪除完裡面所有內容
- String filePath = folderPath;
- filePath = filePath.toString();
- java.io.File myFilePath = new java.io.File(filePath);
- myFilePath.delete(); //刪除空資料夾
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- //刪除指定資料夾下所有檔案
- //param path 資料夾完整絕對路徑
- public static boolean delAllFile(String path) {
- boolean flag = false;
- File file = new File(path);
- if (!file.exists()) {
- return flag;
- }
- if (!file.isDirectory()) {
- return flag;
- }
- String[] tempList = file.list();
- File temp = null;
- for (int i = 0; i < tempList.length; i++) {
- if (path.endsWith(File.separator)) {
- temp = new File(path + tempList[i]);
- } else {
- temp = new File(path + File.separator + tempList[i]);
- }
- if (temp.isFile()) {
- temp.delete();
- }
- if (temp.isDirectory()) {
- delAllFile(path + "/" + tempList[i]);//先刪除資料夾裡面的檔案
- delFolder(path + "/" + tempList[i]);//再刪除空資料夾
- flag = true;
- }
- }
- return flag;
- }
- /**
- * 建立目錄
- * @param dirPath
- */
- static Boolean createDir(String dirPath){
- File dirFile = new File(dirPath);
- return dirFile.mkdirs();
- }
- /**
- * 建立檔案
- * @param filePath
- * @param content
- * @return Boolean
- */
- static Boolean createFile(String filePath,String content){
- Writer writer = null;
- File file = new File(filePath);
- File temp = new File(file.getParent());
- if(!temp.exists()){
- createDir(file.getParent());
- }
- try{
- writer = new OutputStreamWriter(new FileOutputStream(file));
- writer.write( content );
- }catch(Exception e){
- e.printStackTrace();
- return false;
- }finally{
- try{
- if(writer!=null){
- writer.close();
- }
- }catch(Exception e1){
- e1.printStackTrace();
- }
- }
- return true;
- }
- }