java删除文件的问题
指定目录下(路径已经知道),有a.txt b.doc c. d. 等等很多文件,想删除a.txt,如何用java实现??
我表达的意思就是,如何删除已经知道文件名的文件?、就是文件名知道了,想删除它,如何删除
------解决方案--------------------File file = new File(path);
file.delete();
------解决方案--------------------以前写的 删除指定路径下的指定名称的所有文件夹,你把文件夹改成文件就好了,你参考下
public class FileUtils {
/**
* 删除指定目录下的指定文件夹。文件夹名称不区分大小写
*
* @param rootDictionary
* @param dictionary
* @throws Exception
*/
public static void deleteDictionary(String rootDictionary, String dictionary) throws Exception {
deleteDictionary(new File(rootDictionary), dictionary);
}
/**
* 删除指定目录下的指定文件夹。文件夹名称不区分大小写
*
* @param rootDictionary
* @param dictionary
* @throws Exception
*/
public static void deleteDictionary(File rootDictionary, String dictionary) throws Exception {
if (!rootDictionary.exists()) {
throw new Exception("目录<" + rootDictionary + ">不存在!");
}
if (!rootDictionary.isDirectory()) {
throw new Exception("<" + rootDictionary + ">不是一个目录!");
}
File[] files = rootDictionary.listFiles();
if (files == null || files.length == 0) {
return;
}
for (File file : files) {
if (file.isDirectory()) {
if (file.getName().equalsIgnoreCase(dictionary)) {
deleteDictionary(file);
}
else {
deleteDictionary(file, dictionary);
}
}
}
if (rootDictionary.getName().equalsIgnoreCase(dictionary)) {
deleteDictionary(rootDictionary);
}
}
/**
* 删除指定文件夹。文件夹名称不区分大小写
*
* @param dictionary
* @throws Exception
*/
public static void deleteDictionary(String dictionary) throws Exception {
deleteDictionary(new File(dictionary));
}
/**
* 删除指定文件夹。文件夹名称不区分大小写
*
* @param dictionary
* @throws Exception
*/
public static void deleteDictionary(File dictionary) throws Exception {
if (!dictionary.exists()) {
throw new Exception("目录<" + dictionary + ">不存在!");
}
File[] files = dictionary.listFiles();
if (files == null || files.length == 0) {
dictionary.delete();
System.out.println("delete dictionary: " + dictionary.getAbsolutePath());
return;
}
for (File file : files) {
if (file.isDirectory()) {
deleteDictionary(file);
}
else {
file.delete();
System.out.println("delete file: " + file.getAbsolutePath());
}
}
dictionary.delete();
System.out.println("delete dictionary: " + dictionary.getAbsolutePath());
}
public static void main(String[] args) throws Exception {
// 删除menhu路径下所有的.svn文件夹
deleteDictionary("D:\\SRC\\menhu", ".svn");
}
}
------解决方案--------------------
------解决方案--------------------Java code
File file = new File("E:/a.txt");
file.delete();