JAVA 递归批量更改文件后缀名 删除后缀

核心是File.rename()方法的使用

//1.更改后缀
public static void changeSuffix(String pathDir, final String oldSuffix, String newSuffix) {
		File dir = new File(pathDir);
		
		File[] files = dir.listFiles(new FileFilter(){

			@Override
			public boolean accept(File pathname) {
				if (pathname.isDirectory() || pathname.getName().endsWith(oldSuffix)) {
					return true;
				}
				return false;
			}
			
		});
		
		for (File file : files) {
			if (file.isDirectory()) {
				changeSuffix(file.getAbsolutePath(), oldSuffix, newSuffix); // 目录继续
			} else {
				String fileName = file.getAbsolutePath();
				fileName = fileName.substring(0, fileName.indexOf(oldSuffix)) + newSuffix;  // 更改后缀
				file.renameTo(new File(fileName));
			}
		}
	}

// 测试
		String pathDir = "d:\\test";
		String oldSuffix = ".txt";
		String newSuffix = ".txt.bak";
		changeSuffix(pathDir, oldSuffix, newSuffix);


// 2.删除指定后缀名
public static void removeSuffix(String pathDir, final String suffix) {
		File dir = new File(pathDir);
		
		File[] files = dir.listFiles(new FileFilter(){

			@Override
			public boolean accept(File pathname) {
				if (pathname.isDirectory() || pathname.getName().endsWith(suffix)) {
					return true;
				}
				return false;
			}
			
		});
		
		for (File file : files) {
			if (file.isDirectory()) {
				removeSuffix(file.getAbsolutePath(), suffix); // 目录继续
			} else {
				String fileName = file.getAbsolutePath();
				fileName = fileName.substring(0, fileName.indexOf(suffix));  // 删除后缀
				file.renameTo(new File(fileName));
			}
		}
	}

// 测试
String pathDir = "d:\\test";
		String suffix = ".bak";
		removeSuffix(pathDir, suffix);



你可能感兴趣的:(JAVA 递归批量更改文件后缀名 删除后缀)