工具方法:下载文件时碰到相同文件,文件名增加(1) 如果有(1)则下载文件名后缀(2)

来源:互联网 发布:python ui automation 编辑:程序博客网 时间:2024/05/16 01:02
下载方法不提供,本文只提供获取尾部带(1)或(2)这种路径的方法--> String getUniquePath(String path)
其他方法都是子方法

//主方法:获取正确的文件存放路径private static String getUniquePath(String path) {  String resPath = path;  File file = new File(resPath);  while(file.exists())  {   String[] arrayStr = resPath.split("\\.");   if(hasNumSuffix(arrayStr[arrayStr.length-2]))   {    arrayStr[arrayStr.length-2] = plusNumSuffix(arrayStr[arrayStr.length-2]);   }else   {    arrayStr[arrayStr.length-2] = addNumSuffix(arrayStr[arrayStr.length-2]);   }   resPath = mergeStringArray(arrayStr);   file = new File(resPath);  }  return resPath; } private static boolean hasNumSuffix(String str) {  if (str.length() >= 3) {   if (str.charAt(str.length() - 1) == ')' && str.contains("(") && str.indexOf('(') != (str.length() - 2)) {    if (isNumeric(getLastNumInBrackets(str)))     return true;    else     return false;   } else    return false;  } else   return false; } public static boolean isNumeric(String str){     Pattern pattern = Pattern.compile("[0-9]*");     return pattern.matcher(str).matches();  } private static String getLastNumInBrackets(String str) {  String resNumStr;  int leftBracketIndex = str.length()-1;  ArrayList<String> box = new ArrayList<String>();  while(str.charAt(leftBracketIndex)!='(')  {   leftBracketIndex--;  }  resNumStr = str.substring(leftBracketIndex+1, str.length()-1);  return resNumStr; } private static String plusNumSuffix(String str) {  String numStr;  String prefix;  String resStr;  int leftBracketIndex = str.length()-1;  ArrayList<String> box = new ArrayList<String>();  while(str.charAt(leftBracketIndex)!='(')  {   leftBracketIndex--;  }  numStr = str.substring(leftBracketIndex+1, str.length()-1);  int num = Integer.valueOf(numStr);  numStr = String.valueOf(++num);  prefix = str.substring(0,leftBracketIndex+1);  resStr = prefix + numStr + str.charAt(str.length()-1);  return resStr; } private static String addNumSuffix(String str) {  return str+"(1)"; } private static String mergeStringArray(String[] arrayStr) {  StringBuffer sb = new StringBuffer();  for (int i = 0; i < arrayStr.length; i++) {   sb.append(arrayStr[i]);   if (i != arrayStr.length - 1)    sb.append(".");  }  return sb.toString(); }


0 0