我想使用Java创建和删除目录,但它无法正常工作。
File index = new File("/home/Work/Indexer1");
if (!index.exists()) {
index.mkdir();
} else {
index.delete();
if (!index.exists()) {
index.mkdir();
}
}
答案 0 :(得分:146)
只是一个单行。
import org.apache.commons.io.FileUtils;
FileUtils.deleteDirectory(new File(destination));
文档here
答案 1 :(得分:88)
这很有效,虽然跳过目录测试看起来效率不高,但事实并非如此:测试立即发生在listFiles()
。
void deleteDir(File file) {
File[] contents = file.listFiles();
if (contents != null) {
for (File f : contents) {
deleteDir(f);
}
}
file.delete();
}
更新,以避免使用符号链接:
void deleteDir(File file) {
File[] contents = file.listFiles();
if (contents != null) {
for (File f : contents) {
if (! Files.isSymbolicLink(f.toPath())) {
deleteDir(f);
}
}
}
file.delete();
}
答案 2 :(得分:83)
Java无法删除包含数据的文件夹。您必须在删除文件夹之前删除所有文件。
使用类似:
String[]entries = index.list();
for(String s: entries){
File currentFile = new File(index.getPath(),s);
currentFile.delete();
}
然后您应该可以使用index.delete()
删除该文件夹
未经测试!
答案 3 :(得分:21)
在JDK 7中,您可以使用Files.walkFileTree()
和Files.deleteIfExists()
删除文件树。
在JDK 6中,一种可能的方法是使用Apache Commons中的FileUtils.deleteQuietly,它将删除文件,目录或包含文件和子目录的目录。
答案 4 :(得分:18)
使用Apache Commons-IO,它遵循单行:
import org.apache.commons.io.FileUtils;
FileUtils.forceDelete(new File(destination));
这比FileUtils.deleteDirectory
(稍微)更高效。
答案 5 :(得分:16)
我更喜欢java 8上的这个解决方案:
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
答案 6 :(得分:9)
我的基本递归版本,使用旧版本的JDK:
public static void deleteFile(File element) {
if (element.isDirectory()) {
for (File sub : element.listFiles()) {
deleteFile(sub);
}
}
element.delete();
}
答案 7 :(得分:8)
这是Java 7+
的最佳解决方案:
public static void deleteDirectory(String directoryFilePath) throws IOException
{
Path directory = Paths.get(directoryFilePath);
if (Files.exists(directory))
{
Files.walkFileTree(directory, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException
{
Files.delete(path);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException
{
Files.delete(directory);
return FileVisitResult.CONTINUE;
}
});
}
}
答案 8 :(得分:4)
我最喜欢这个解决方案。它不使用第三方库,而是使用Java 7的NIO2。
/**
* Deletes Folder with all of its content
*
* @param folder path to folder which should be deleted
*/
public static void deleteFolderAndItsContent(final Path folder) throws IOException {
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
throw exc;
}
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
答案 9 :(得分:3)
你可以试试这个
public static void deleteDir(File dirFile) {
if (dirFile.isDirectory()) {
File[] dirs = dirFile.listFiles();
for (File dir: dirs) {
deleteDir(dir);
}
}
dirFile.delete();
}
答案 10 :(得分:3)
番石榴21+救援。仅在没有指向要删除的目录的符号链接时使用。
com.google.common.io.MoreFiles.deleteRecursively(
file.toPath(),
RecursiveDeleteOption.ALLOW_INSECURE
) ;
(这个问题很好地被谷歌编入索引,因此其他人使用番石榴可能会很乐意找到这个答案,即使它与其他地方的其他答案是多余的。)
答案 11 :(得分:2)
在此
index.delete();
if (!index.exists())
{
index.mkdir();
}
你正在打电话
if (!index.exists())
{
index.mkdir();
}
后
index.delete();
这意味着您在删除后再次创建文件
File.delete()返回一个布尔值。如果要检查,则执行System.out.println(index.delete());
如果获得true
,则表示文件已删除
File index = new File("/home/Work/Indexer1");
if (!index.exists())
{
index.mkdir();
}
else{
System.out.println(index.delete());//If you get true then file is deleted
if (!index.exists())
{
index.mkdir();// here you are creating again after deleting the file
}
}
来自下面给出的comments,更新的答案就像这样
File f=new File("full_path");//full path like c:/home/ri
if(f.exists())
{
f.delete();
}
else
{
try {
//f.createNewFile();//this will create a file
f.mkdir();//this create a folder
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 12 :(得分:1)
如果你有子文件夹,你会发现Cemron答案的麻烦。所以你应该创建一个像这样工作的方法:
private void deleteTempFile(File tempFile) {
try
{
if(tempFile.isDirectory()){
File[] entries = tempFile.listFiles();
for(File currentFile: entries){
deleteTempFile(currentFile);
}
tempFile.delete();
}else{
tempFile.delete();
}
getLogger().info("DELETED Temporal File: " + tempFile.getPath());
}
catch(Throwable t)
{
getLogger().error("Could not DELETE file: " + tempFile.getPath(), t);
}
}
答案 13 :(得分:1)
目录不能简单地删除它是否有文件所以你可能需要先删除里面的文件然后再删除目录
public class DeleteFileFolder {
public DeleteFileFolder(String path) {
File file = new File(path);
if(file.exists())
{
do{
delete(file);
}while(file.exists());
}else
{
System.out.println("File or Folder not found : "+path);
}
}
private void delete(File file)
{
if(file.isDirectory())
{
String fileList[] = file.list();
if(fileList.length == 0)
{
System.out.println("Deleting Directory : "+file.getPath());
file.delete();
}else
{
int size = fileList.length;
for(int i = 0 ; i < size ; i++)
{
String fileName = fileList[i];
System.out.println("File path : "+file.getPath()+" and name :"+fileName);
String fullPath = file.getPath()+"/"+fileName;
File fileOrFolder = new File(fullPath);
System.out.println("Full Path :"+fileOrFolder.getPath());
delete(fileOrFolder);
}
}
}else
{
System.out.println("Deleting file : "+file.getPath());
file.delete();
}
}
答案 14 :(得分:1)
如果子目录存在,您可以进行递归调用
import java.io.File;
class DeleteDir {
public static void main(String args[]) {
deleteDirectory(new File(args[0]));
}
static public boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
return( path.delete() );
}
}
答案 15 :(得分:1)
我们可以使用spring-core
依赖项;
boolean result = FileSystemUtils.deleteRecursively(file);
答案 16 :(得分:1)
大多数引用JDK类的答案(甚至是最近的答案)都依赖于File.delete()
,但这是一个有缺陷的API,因为操作可能会静默失败。
java.io.File.delete()
方法文档指出:
请注意,
java.nio.file.Files
类将delete
方法定义为 无法删除文件时抛出IOException
。这对于 错误报告并诊断为什么无法删除文件。
作为替换,您应该支持Files.delete(Path p)
并抛出一条带有错误消息的IOException
。
实际代码可以写为:
Path index = Paths.get("/home/Work/Indexer1");
if (!Files.exists(index)) {
index = Files.createDirectories(index);
} else {
Files.walk(index)
.sorted(Comparator.reverseOrder()) // as the file tree is traversed depth-first and that deleted dirs have to be empty
.forEach(t -> {
try {
Files.delete(t);
} catch (IOException e) {
// LOG the exception and potentially stop the processing
}
});
if (!Files.exists(index)) {
index = Files.createDirectories(index);
}
}
答案 17 :(得分:1)
您可以使用 FileUtils.deleteDirectory 。 JAVA无法使用 File.delete()删除非空文件夹。
答案 18 :(得分:0)
import org.apache.commons.io.FileUtils;
List<String> directory = new ArrayList();
directory.add("test-output");
directory.add("Reports/executions");
directory.add("Reports/index.html");
directory.add("Reports/report.properties");
for(int count = 0 ; count < directory.size() ; count ++)
{
String destination = directory.get(count);
deleteDirectory(destination);
}
public void deleteDirectory(String path) {
File file = new File(path);
if(file.isDirectory()){
System.out.println("Deleting Directory :" + path);
try {
FileUtils.deleteDirectory(new File(path)); //deletes the whole folder
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
System.out.println("Deleting File :" + path);
//it is a simple file. Proceed for deletion
file.delete();
}
}
像魅力一样工作。对于文件夹和文件。萨拉姆:)
答案 19 :(得分:0)
这是一种简单的方法:
public void deleteDirectory(String directoryPath) {
new Thread(new Runnable() {
public void run() {
for(String e: new File(directoryPath).list()) {
if(new File(e).isDirectory())
deleteDirectory(e);
else
new File(e).delete();
}
}
}).start();
}
答案 20 :(得分:0)
您还可以使用它来删除包含子文件夹和文件的文件夹。
首先,创建一个递归函数。
private void recursiveDelete(File file){
if(file.list().length > 0){
String[] list = file.list();
for(String is: list){
File currentFile = new File(file.getPath(),is);
if(currentFile.isDirectory()){
recursiveDelete(currentFile);
}else{
currentFile.delete();
}
}
}else {
file.delete();
}
}
然后,从您的初始函数中使用while循环调用递归。
private boolean deleteFolderContainingSubFoldersAndFiles(){
boolean deleted = false;
File folderToDelete = new File("C:/mainFolderDirectoryHere");
while(folderToDelete != null && folderToDelete.isDirectory()){
recursiveDelete(folderToDelete);
}
return deleted;
}
答案 21 :(得分:0)
2020在这里:)
与Apache commons io FileUtils相比,与“纯” Java变体相反,文件夹不需要为空即可将其删除。为了给您更好的概览,我在此处列出了变体,以下3种可能会出于各种原因抛出异常:
以下变体从不抛出异常(即使文件为空!)
要知道的另一件事是处理symbolic links,它将删除符号链接而不是目标文件夹……要小心。
还请记住,删除大文件或文件夹可能是阻止操作一段时间……因此,如果您不介意异步运行,请执行此操作(在后台线程中)例如通过执行程序)。
答案 22 :(得分:0)
另一种选择是使用Spring的org.springframework.util.FileSystemUtils
相关方法,该方法将递归删除目录的所有内容。
File directoryToDelete = new File(<your_directory_path_to_delete>);
FileSystemUtils.deleteRecursively(directoryToDelete);
那样就可以了!
答案 23 :(得分:0)
如前所述,Java无法删除包含文件的文件夹,因此先删除文件,然后再删除文件夹。
这是一个简单的示例:
import org.apache.commons.io.FileUtils;
// First, remove files from into the folder
FileUtils.cleanDirectory(folder/path);
// Then, remove the folder
FileUtils.deleteDirectory(folder/path);
或者:
FileUtils.forceDelete(new File(destination))
答案 24 :(得分:0)
你可以尝试如下
File dir = new File("path");
if (dir.isDirectory())
{
dir.delete();
}
如果文件夹中有子文件夹,则可能需要以递归方式删除它们。
答案 25 :(得分:0)
private void deleteFileOrFolder(File file){
try {
for (File f : file.listFiles()) {
f.delete();
deleteFileOrFolder(f);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
答案 26 :(得分:-1)
import java.io.File;
public class Main{
public static void main(String[] args) throws Exception {
deleteDir(new File("c:\\temp"));
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir (new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
System.out.println("The directory is deleted.");
}
}
答案 27 :(得分:-1)
其中一些答案看起来不必要很长:
if (directory.exists()) {
for (File file : directory.listFiles()) {
file.delete();
}
directory.delete();
}
也适用于子目录。
答案 28 :(得分:-1)
将其从其他部分
中删除File index = new File("/home/Work/Indexer1");
if (!index.exists())
{
index.mkdir();
System.out.println("Dir Not present. Creating new one!");
}
index.delete();
System.out.println("File deleted successfully");
答案 29 :(得分:-3)
您可以使用此功能
public function actionMyAccount()
{
$model = new User();
if ( Yii::$app->user->isGuest )
{
return $this->goHome();
}
//if ( Yii::$app->request->post() AND $model->validate())
if ( Yii::$app->request->post())
{
if($model->load(Yii::$app->request->post()) )
{
$model->save();
Yii::$app->session->setFlash('message', "Account has been updated!");
}
}
else
{
$model = User::getCurrentUser();
}
return $this->render('my-account', ['model' => $model,]);
}