java 删除目录下特定文件
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class FileTest {
/**
* 删除目录下特定文件
* @param path 目录
* @param fileName 待删除文件名
* @return
*/
public static boolean deleteFile(String path, String fileName){
File directory = new File(path);
File[] files = directory.listFiles();//把目录directory下的所有文件放在数组files
if(files.length == 0){
return false;
}
for(File file : files){
if(file.getName().equals(fileName)){ //若文件名与待删除文件名相同,则删除文件
file.delete();
return true;
}
}
return false;
}
public static void main(String[] args) {
//建立目录F:\com\jin
File f = new File("F:"+File.separator+ "com"+File.separator+"jin") ;
f.mkdirs() ;// 创建文件夹
FileOutputStream fileOutputStream;
if(f.exists()){
System.out.println(f.getAbsolutePath());
System.out.println("已经创建好目录了");
}
try {
fileOutputStream = new FileOutputStream(new File("F:/com/jin/22.txt"));
fileOutputStream.write("hello world".getBytes(), 0, 5);
fileOutputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//用于测试,可注释掉
System.out.println(deleteFile("F:"+File.separator+ "com"+File.separator+"jin","22.txt"));
}
}