package Test;
import java.io.File;import java.io.IOException;public class CreateFileTest {/*** 建立單個檔案* @param destFileName 檔案名稱* @return 建立成功返回true,否則返回false*/public static boolean CreateFile(String destFileName) { File file = new File(destFileName); if (file.exists()) { System.out.println("建立單個檔案" + destFileName + "失敗,目標檔案已存在!"); return false; } if (destFileName.endsWith(File.separator)) { System.out.println("建立單個檔案" + destFileName + "失敗,目標不能是目錄!"); return false; } if (!file.getParentFile().exists()) { System.out.println("目標檔案所在路徑不存在,準備建立。。。"); if (!file.getParentFile().mkdirs()) { System.out.println("建立目錄檔案所在的目錄失敗!"); return false; } } // 建立目標檔案 try { if (file.createNewFile()) { System.out.println("建立單個檔案" + destFileName + "成功!"); return true; } else { System.out.println("建立單個檔案" + destFileName + "失敗!"); return false; } } catch (IOException e) { e.printStackTrace(); System.out.println("建立單個檔案" + destFileName + "失敗!"); return false; }}/*** 建立目錄* @param destDirName 目標目錄名* @return 目錄建立成功返回true,否則返回false*/public static boolean createDir(String destDirName) { File dir = new File(destDirName); if(dir.exists()) { System.out.println("建立目錄" + destDirName + "失敗,目標目錄已存在!"); return false; } if(!destDirName.endsWith(File.separator)) destDirName = destDirName + File.separator; // 建立單個目錄 if(dir.mkdirs()) { System.out.println("建立目錄" + destDirName + "成功!"); return true; } else { System.out.println("建立目錄" + destDirName + "成功!"); return false; }}/*** 建立臨時檔案* @param prefix 臨時檔案的首碼* @param suffix 臨時檔案的尾碼* @param dirName 臨時檔案所在的目錄,如果輸入null,則在使用者的文檔目錄下建立臨時檔案* @return 臨時檔案建立成功返回抽象路徑名的規範路徑名字串,否則返回null*/public static String createTempFile(String prefix, String suffix, String dirName) { File tempFile = null; try{ if(dirName == null) { // 在預設資料夾下建立臨時檔案 tempFile = File.createTempFile(prefix, suffix); return tempFile.getCanonicalPath(); }else { File dir = new File(dirName); // 如果臨時檔案所在目錄不存在,首先建立 if(!dir.exists()) { if(!CreateFileTest.createDir(dirName)){ System.out.println("建立臨時檔案失敗,不能建立臨時檔案所在目錄!"); return null; } } tempFile = File.createTempFile(prefix, suffix, dir); return tempFile.getCanonicalPath(); } } catch(IOException e) { e.printStackTrace(); System.out.println("建立臨時檔案失敗" + e.getMessage()); return null; }}public static void main(String[] args) {// 建立目錄 String dirName = "d:/test/test0/test1"; CreateFileTest.createDir(dirName); // 建立檔案 String fileName = dirName + "/test2/testFile.txt"; CreateFileTest.CreateFile(fileName); // 建立臨時檔案 String prefix = "temp"; String suffix = ".txt"; for(int i = 0; i < 10; i++) { System.out.println("建立了臨時檔案:" + CreateFileTest.createTempFile(prefix, suffix, dirName)); }}}