1. 程式人生 > >java在系統中建立和刪除含有路徑的檔案

java在系統中建立和刪除含有路徑的檔案

package com.apk.openUser.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//建立檔案
public class OperateFileUtil {
	    
	    public static void creatFile(String filePath, String fileName) {
	        File folder = new File(filePath);
	        //資料夾路徑不存在
	        if (!folder.exists() && !folder.isDirectory()) {
	            System.out.println("資料夾路徑不存在,建立路徑:" + filePath);
	            folder.mkdirs();
	        } else {
	            System.out.println("資料夾路徑存在:" + filePath);
	        }

	        // 如果檔案不存在就建立
	        File file = new File(filePath + fileName);
	        if (!file.exists()) {
	            System.out.println("檔案不存在,建立檔案:" + filePath + fileName);
	            try {
	                file.createNewFile();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        } else {
	            System.out.println("檔案已存在,檔案為:" + filePath + fileName);
	        }
	    }
	    public static boolean deletefile(String delpath) throws Exception {
	    	Boolean bo = false;
	        try {

	            File file = new File(delpath);
	            // 當且僅當此抽象路徑名錶示的檔案存在且 是一個目錄時,返回 true
	            if (!file.exists()) {
	            	System.out.println("刪除檔案失敗:" + file + "不存在!");
	            	bo = false;
	            } else {
	            	if (!file.isDirectory()) {
	            		file.delete();
	            	} else if (file.isDirectory()) {
	            		String[] filelist = file.list();
	            		for (int i = 0; i < filelist.length; i++) {
	            			//File.separator,自動識別系統中路徑的分隔符/還是\\.
	            			File delfile = new File(delpath +File.separator+ filelist[i]);
	            			if (!delfile.isDirectory()) {
	            				delfile.delete();
	            				System.out.println(delfile.getAbsolutePath() + "刪除檔案成功");
	            			} else if (delfile.isDirectory()) {
	            				deletefile(delpath +File.separator+ filelist[i]);
	            			}
	            		}
	            		System.out.println(file.getAbsolutePath() + "刪除成功");
	            		file.delete();
	            	}
	            	bo = true;
	            }

	        } catch (FileNotFoundException e) {
	        	System.out.println("deletefile() Exception:" + e.getMessage());
	        }
	        return bo;
	    }

	public static void main(String[] args) throws FileNotFoundException {
	        FileOutputStream outFile = null;

	        try {
	            /*creatFile(FILE_PATH, FILE_NAME);
	            outFile = new FileOutputStream(FILE_PATH + FILE_NAME);*/
	        	String path = "D:/8F100";
	        	System.out.println(deletefile(path));
	            //後續檔案操作
	        } catch (Exception e) {
	            e.printStackTrace();
	        } 
	}

}