版权声明: https://blog.csdn.net/qq_36907589/article/details/83751819
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;
/**
*
*递归读取某个目录下的所有文件
*
*/
public class ReadFileUtil {
private static Logger logger = Logger.getLogger("读取文件异常:");
//filePath 要读取的文件夹路径
/**
* 递归读取某个目录下的所有文件
* @param filePath
* @return
*/
public static HashMap<String, String> getReadFileMap(String filePath) {
HashMap<String, String> hashMap = new HashMap<>();
File file = new File(filePath);
File[] files = file.listFiles();//获取目录下的所有文件或文件夹
if (files == null) {// 如果目录为空,直接退出
logger.info("读取文件目录为空!");
return null;
}
// 遍历,目录下的所有文件
for (File f : files) {
if (f.isFile()) {
hashMap.put(f.getName(), f.getAbsolutePath());//存储文件名字+绝对路径
}
}
return hashMap;
}
/**
* 修改文件版本后缀
* @param pathUpdate 文件绝对路径
* @param version 版本号-递增
*/
public static void getUpdateFileNameVersion(String pathUpdate,String version) {
File oldFile = new File(pathUpdate);
if (!oldFile.exists()){
try {
oldFile.createNewFile();//没有就创建
} catch (IOException e) {
System.out.println("创建文件失败");
e.printStackTrace();
}
}
System.out.println("修改前文件名称是:"+oldFile.getName());
String rootPath = oldFile.getParent();
System.out.println("根路径是:"+rootPath);
String fileName = oldFile.getName();
//获取文件前缀
String fileNameQian = fileName.substring(0, fileName.lastIndexOf("."));
System.out.println("前缀:"+fileNameQian);
//获取文件后缀
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
File newFile = new File(rootPath + File.separator + fileNameQian + version+"."+suffix);
System.out.println("修改后文件名称是:"+newFile.getName());
if (oldFile.renameTo(newFile)){
System.out.println("修改成功!");
}else {
System.out.println("修改失败!");
}
}
}
测试:
@Test
public void testWord(){
String path1 ="E:/测试读取文件";
HashMap<String, String> fileMap = ReadFileUtil.getReadFileMap(path1);
Iterator<Map.Entry<String, String>> iterator = fileMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> next = iterator.next();
String key = next.getKey();
String value = next.getValue();
System.out.println("读取的文件名: "+key +" "+"文件绝对路径: "+value);
}
}
//打开文件
@Test
public void testOprnWord(){
/**
* 根据路径打开查看文件
*/
final Runtime runtime = Runtime.getRuntime();
Process process = null;
final String cmd = "rundll32 url.dll FileProtocolHandler file://E:\\测试读取文件\\对比2.doc";//要打开的文件路径。
try {
process = runtime.exec(cmd);
} catch (final Exception e) {
System.out.println("Error exec!");
}
}