注释下面部分可满足我现在需求
public class RenameFileUtil {
/**
* @param from fileInfo[0]: toPrefix;
* fileInfo[1]:toSuffix;
* @return
*/
public static String[] getFileInfo(File from) {
String fileName = from.getName();
int index = fileName.lastIndexOf(".");
String toPrefix = "";
String toSuffix = "";
if (index == -1) {
toPrefix = fileName;
} else {
toPrefix = fileName.substring(0, index);
toSuffix = fileName.substring(index, fileName.length());
}
return new String[]{toPrefix, toSuffix};
}
/**
* sdcard/pic/tanyang.jpg
* <p>
* toPrefix: tanyang
* toSuffix: tanyang.jpg
*
* @param from 文件路径
* @param toPrefix 文件名
* @param toSuffix 后缀名
* @return
*/
public static File createOrRenameFile(File from, String toPrefix, String toSuffix) {
File directory = from.getParentFile();
if (!directory.exists()) {
if (directory.mkdir()) {
System.out.println("Created directory " + directory.getAbsolutePath());
}
}
File newFile = new File(directory, toPrefix + toSuffix);
for (int i = 1; newFile.exists() && i < Integer.MAX_VALUE; i++) {
newFile = new File(directory, toPrefix + '(' + i + ')' + toSuffix);
}
//不执行renameTo(),会把原文件删除
//不需要执行renameTo方法,直接返回重命名后的文件就可以
/*if (!from.renameTo(newFile)) {
System.out.println("Couldn't rename file to " + newFile.getAbsolutePath());
return from;
}*/
return newFile;
}
}