UI自动化脚本中,经常需要选取磁盘上的文件进行操作。
当文件名不固定,用脚本进行键鼠操作又繁琐的情况下,直接获得带有完整路径的文件名,反而更加方便。
package tools;
import java.io.File;
import java.util.TreeMap;
public class FileOperate {
static String newFileName;
static String largeFileName;
static String sortFileName;
public static String getNewFileName() {//获取最新文件名称
TreeMap<Long,File> tm = new TreeMap<Long,File>();
File file = new File("E:\\");//艳艳,这个可以作为参数传进来。也可以写死
File subFile[] = file.listFiles();
int fileNum = subFile.length;
for (int i = 0; i < fileNum; i++) {//排序核心代码,使用了lastModified方法
Long tempLong = new Long(subFile[i].lastModified());
tm.put(tempLong, subFile[i]);
}
newFileName = tm.get(tm.lastKey()).getPath();
return newFileName;
}
public static String getLargeFileName() {//获取最大文件名称
TreeMap<Long,File> tm = new TreeMap<Long,File>();
File file = new File("E:\\");
File subFile[] = file.listFiles();
int fileNum = subFile.length;
for (int i = 0; i < fileNum; i++) {
Long tempLong = new Long(subFile[i].length());
tm.put(tempLong, subFile[i]);
}
largeFileName = tm.get(tm.lastKey()).getPath();
return largeFileName;
}
public static String getSortFileName() {//获取排序最后一个文件名称
TreeMap<String,File> tm = new TreeMap<String,File>();
File file = new File("E:\\");
File subFile[] = file.listFiles();
int fileNum = subFile.length;
for (int i = 0; i < fileNum; i++) {
String tempLong = new String(subFile[i].getName());
tm.put(tempLong, subFile[i]);
}
sortFileName = tm.get(tm.lastKey()).getPath();
return sortFileName;
}
public static String LocalFile() {
try {
File directory = new File("");//设定为当前文件夹
String path = directory.getCanonicalPath();//获取标准的路径 ,返回类型为String
return(path);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return("error");
}
}
}
😎上面的代码作为抛砖引玉,实际使用中,可以根据需要,封装新的方法供外部脚本调用。