經常使用的工具類-CreateFileUtil,Redirect

class CreateFileUtil {
  
  public static String createTempFile(String prefix, String suffix, String dirName) {  
    File tempFile = null;  
    if (dirName == null) {  
        try{  
            //在默認文件夾下建立臨時文件  
            tempFile = File.createTempFile(prefix, suffix);  
            //返回臨時文件的路徑  
            return tempFile.getCanonicalPath();  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("建立臨時文件失敗!" + e.getMessage());  
            return null;  
        }  
    } else {  
        File dir = new File(dirName);  
        //若是臨時文件所在目錄不存在,首先建立  
        if (!dir.exists()) {  
            if (!CreateFileUtil.createDir(dirName)) {  
                System.out.println("建立臨時文件失敗,不能建立臨時文件所在的目錄!");  
                return null;  
            }  
        }  
        try {  
            //在指定目錄下建立臨時文件  
            tempFile = File.createTempFile(prefix, suffix, dir);  
            return tempFile.getCanonicalPath();  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("建立臨時文件失敗!" + e.getMessage());  
            return null;  
        }  
    }  
}  
  
  public static boolean createDir(String destDirName) {  
    File dir = new File(destDirName);  
    if (dir.exists()) {   
        return false;  
    }  
    if (!destDirName.endsWith(File.separator)) {  
        destDirName = destDirName + File.separator;  
    }  
    //建立目錄  
    if (dir.mkdirs()) {  
        return true;  
    } else {  
        return false;  
    }  
  }  
  
  public static boolean createFile(String destFileName) {
    File file = new File(destFileName);
    if(file.exists()) {
      return false;
    }
    if(destFileName.endsWith(File.separator)) {
      return false;  
    }
    
  //判斷目標文件所在的目錄是否存在  
    if(!file.getParentFile().exists()) {  
        //若是目標文件所在的目錄不存在,則建立父目錄  
        if(!file.getParentFile().mkdirs()) {  
            return false;  
        }  
    }  
    //建立目標文件  
    try {  
        if (file.createNewFile()) {  
            return true;  
        } else {   
            return false;  
        }  
    } catch (IOException e) {  
        e.printStackTrace();  
        System.out.println("建立單個文件" + destFileName + "失敗!" + e.getMessage());  
        return false;  
    }  
  }

}

class Redirect {
  //將打印重定向到一個文件
  public static void start(String filename) {
    CreateFileUtil.createFile(filename);
    File file = new File(filename);
    try{
        System.setOut(new PrintStream(new FileOutputStream(file, true)));
    }catch(FileNotFoundException e){
        e.printStackTrace();
    }   
  }
}
相關文章
相關標籤/搜索