Удаление файлов в папке java

Удаление файлов в папке java

Класс File, определенный в пакете java.io, не работает напрямую с потоками. Его задачей является управление информацией о файлах и каталогах. Хотя на уровне операционной системы файлы и каталоги отличаются, но в Java они описываются одним классом File.

В зависимости от того, что должен представлять объект File — файл или каталог, мы можем использовать один из конструкторов для создания объекта:

File(String путь_к_каталогу) File(String путь_к_каталогу, String имя_файла) File(File каталог, String имя_файла)
// создаем объект File для каталога File dir1 = new File("C://SomeDir"); // создаем объекты для файлов, которые находятся в каталоге File file1 = new File("C://SomeDir", "Hello.txt"); File file2 = new File(dir1, "Hello2.txt");

Класс File имеет ряд методов, которые позволяют управлять файлами и каталогами. Рассмотрим некоторые из них:

  • boolean createNewFile() : создает новый файл по пути, который передан в конструктор. В случае удачного создания возвращает true, иначе false
  • boolean delete() : удаляет каталог или файл по пути, который передан в конструктор. При удачном удалении возвращает true.
  • boolean exists() : проверяет, существует ли по указанному в конструкторе пути файл или каталог. И если файл или каталог существует, то возвращает true, иначе возвращает false
  • String getAbsolutePath() : возвращает абсолютный путь для пути, переданного в конструктор объекта
  • String getName() : возвращает краткое имя файла или каталога
  • String getParent() : возвращает имя родительского каталога
  • boolean isDirectory() : возвращает значение true, если по указанному пути располагается каталог
  • boolean isFile() : возвращает значение true, если по указанному пути находится файл
  • boolean isHidden() : возвращает значение true, если каталог или файл являются скрытыми
  • long length() : возвращает размер файла в байтах
  • long lastModified() : возвращает время последнего изменения файла или каталога. Значение представляет количество миллисекунд, прошедших с начала эпохи Unix
  • String[] list() : возвращает массив файлов и подкаталогов, которые находятся в определенном каталоге
  • File[] listFiles() : возвращает массив файлов и подкаталогов, которые находятся в определенном каталоге
  • boolean mkdir() : создает новый каталог и при удачном создании возвращает значение true
  • boolean renameTo(File dest) : переименовывает файл или каталог
Читайте также:  Корзина для товаров html

Работа с каталогами

Если объект File представляет каталог, то его метод isDirectory() возвращает true . И поэтому мы можем получить его содержимое — вложенные подкаталоги и файлы с помощью методов list() и listFiles() . Получим все подкаталоги и файлы в определенном каталоге:

import java.io.File; public class Program < public static void main(String[] args) < // определяем объект для каталога File dir = new File("C://SomeDir"); // если объект представляет каталог if(dir.isDirectory()) < // получаем все вложенные объекты в каталоге for(File item : dir.listFiles())< if(item.isDirectory())< System.out.println(item.getName() + " \t folder"); >else < System.out.println(item.getName() + "\t file"); >> > > >

Теперь выполним еще ряд операций с каталогами, как удаление, переименование и создание:

import java.io.File; public class Program < public static void main(String[] args) < // определяем объект для каталога File dir = new File("C://SomeDir//NewDir"); boolean created = dir.mkdir(); if(created) System.out.println("Folder has been created"); // переименуем каталог File newDir = new File("C://SomeDir//NewDirRenamed"); dir.renameTo(newDir); // удалим каталог boolean deleted = newDir.delete(); if(deleted) System.out.println("Folder has been deleted"); >>

Работа с файлами

Работа с файлами аналогична работе с каталога. Например, получим данные по одному из файлов и создадим еще один файл:

import java.io.File; import java.io.IOException; public class Program < public static void main(String[] args) < // определяем объект для каталога File myFile = new File("C://SomeDir//notes.txt"); System.out.println("File name: " + myFile.getName()); System.out.println("Parent folder: " + myFile.getParent()); if(myFile.exists()) System.out.println("File exists"); else System.out.println("File not found"); System.out.println("File size: " + myFile.length()); if(myFile.canRead()) System.out.println("File can be read"); else System.out.println("File can not be read"); if(myFile.canWrite()) System.out.println("File can be written"); else System.out.println("File can not be written"); // создадим новый файл File newFile = new File("C://SomeDir//MyFile"); try < boolean created = newFile.createNewFile(); if(created) System.out.println("File has been created"); >catch(IOException ex) < System.out.println(ex.getMessage()); >> >

При создании нового файла метод createNewFile() в случае неудачи выбрасывает исключение IOException , поэтому нам надо его отлавливать, например, в блоке try. catch, как делается в примере выше.

Читайте также:  Php загрузить html в переменную

Источник

How to delete a directory with files in Java — Example

Deleting an empty directory is easy in Java, just use the delete() method of java.io.File class, but deleting a directory with files is unfortunately not easy. You just can’t delete a folder if it contains files or sub folders. Calling delete() method on a File instance representing a non-empty directory will just return false without removing the directory. In order to delete this folder, you need to delete all files and subdirectories inside this folder. This may seem cumbersome, but unfortunately, there is no method that can delete a directory with files in Java, not even on Java 7 Files and Paths class.

So there are two choices, either you write your own method to recursively delete all files and folder before deleting a directory, or alternatively, you can use an open-source utility library like Apache Commons IO which will do this for you.

BTW, If you have to do this without using any third party library then you can use the example shown in this tutorial. You know what, I have asked this question couple of times to Java developers and only 3 out of 10 knows that you cannot delete a directory with files in Java.

I am not surprised because this is the kind of detail which is not obvious. Until you do it, you don’t know this. Java isn’t able to delete folders with data in it. You have to delete all files before deleting the folder, as shown in the first example of this tutorial. Java 7 got much better with files and directory support but there also, unfortunately, no direct method to delete a directory with files. Though, In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files.

Java Program to delete non empty directory in Java

Primary method to delete a file or directory in Java was File.delete() method form java.io package. This method can be used to delete a file or a nonempty directory but fail silently when it comes to deleting folder with files. If you ignore return value of this method, which is false if it failed to delete directory then you will never know that whether your program failed to remove some directory and I have seen many developers hit by this bullet. Thankfully, JDK 7 added another delete() method in Files utility class to delete file and directory, which throws IOException when a file cannot be deleted. This is really useful for troubleshooting purpose e.g. to find out why a file cannot be deleted. There is one more similar method, Files.deleteIfExists() , which is slightly more readable than original delete() method from File class.

Now coming back to our original question, how to delete a folder with files or sub folder inside it. Well, we need to write a program which can recursively check all files and folder and delete them before deleting the top level directory. In this example, I have create a directory structure with one directory containing a file and a sub-directory containing another file and tried to delete the top directory using our method.

In this program, I have two overloaded method, deleteDirectory(File file) and deleteDirectory(String path) to demonstrate the right and wrong way to delete a directory in Java. The method which accepts a String argument, first print all contents of directory without printing contents of sub directory and then just call delete method on the directory we want to delete. This method cannot remove a non-empty directory, so it failed and return false which is captured in method. The right way to delete a directory with files is to recursively delete any sub directory and files inside it, which is demonstrated in deleteDirectory(File) method.

This method first check if the given File instance represent a directory, if yes then it list all files and sub directory and recursively call the same method to delete each of them. This allows program to remove files inside a sub folder before removing it. Once everything inside given directory is deleted, it proceed to delete the given folder.

import java.io.File; /** * Java Program to delete directory with sub directories and files on it * In this example, we have a directory tree as one/ abc.txt * two/ cde.txt and we will try to delete top level directory one here. * * @author Javin Paul */ public class FileDeleteDemo < public static void main(String args[]) < deleteDirectory("one"); // wrong way to remove a directory in Java deleteDirectory(new File("one")); //right way to remove directory in Java > /* * Right way to delete a non empty directory in Java */ public static boolean deleteDirectory(File dir) < if (dir.isDirectory()) < File[] children = dir.listFiles(); for (int i = 0; i  children.length; i++) < boolean success = deleteDirectory(children[i]); if (!success) < return false; > > > // either file or an empty directory System.out.println("removing file or directory : " + dir.getName()); return dir.delete(); > /* * Incorrect way to delete a directory in Java */ public static void deleteDirectory(String file) < File directory = new File(file); File[] children = directory.listFiles(); for (File child : children) < System.out.println(child.getAbsolutePath()); > // let's delete this directory // it will not work because directory has sub-directory // which has files inside it. // In order to delete a directory, // you need to first delete its files or contents. boolean result = directory.delete(); if (result) < System.out.printf("Directory '%s' is successfully deleted", directory.getAbsolutePath()); > else < System.out.printf("Failed to delete directory '%s' %n", directory.getAbsolutePath()); > > > D:\Programs\Test\one\abc.txt D:\Programs\Test\one\two Failed to delete directory 'D:\Programs\Test\one' removing file or directory : abc.txt removing file or directory : cde.txt removing file or directory : two removing file or directory : one

That’s all on how to delete non-empty directory with files in Java. As you can see in output the method which takes String path is not able to delete our directory with files «one», instead it failed, while our second method has recursively deleted everything inside this top-level directory, you can see files are deleted before directory to make them empty. I have not tested this code heavily but it should work on all Java versions starting from Java 1.2

  • How to read File in one line in Java 8? (example)
  • How to read Microsoft XLS file in Java? (example)
  • How to work with RandomAccessFile in Java? (demo)
  • How to create File and Directory in Java? (solution)
  • How to read/write text files in Java? (solution)
  • How to read/write Properties files in Java? (example)
  • How to read File line by line in Java using BufferedReader? (example)
  • How to use Memory Mapped File in Java? (code)
  • How to make hidden file in Java? (program)
  • How to copy File in Java? (solution)
  • How to check File Permission in Java? (program)
  • Difference between getPath(), getCannonicalPath() and getAbsolutePath() in Java? (answer)
  • How to change File Permission in Java? (solution)
  • Right way to Read Zip Files in Java (example)
  • How to check hidden file in Java? (solution)

Источник

Удаление файлов в папке java

Path testFile = Paths.get(«C:\\Users\\jleom\\Desktop\\java\\javarush task\\test.txt»); Path testFile2 = Paths.get(«C:\\Users\\jleom\\Desktop»); System.out.println(testFile.relativize(testFile2));

Класс Path и класс Paths предназначены для работы с файловой системой в Java, однако они предоставляют разные функции и методы. Path — это интерфейс, который определяет методы для работы с путями к файлам и каталогам в файловой системе. Он предоставляет ряд методов для работы с путями, таких как resolve(), relativize(), getParent(), getFileName(), toAbsolutePath() и другие. Paths — это утилитный класс, который предоставляет статические методы для создания экземпляров класса Path. Он не имеет методов для работы с путями напрямую, но предоставляет методы для создания экземпляров Path из строковых значений или URI. Еще методы по классу Paths: getFileSystem(): возвращает объект FileSystem, представляющий файловую систему, которой принадлежит данный путь. getDefault(): возвращает объект FileSystem, представляющий файловую систему по умолчанию. getTempDirectory(): возвращает объект типа Path, представляющий временный каталог. getHomeDirectory(): возвращает объект типа Path, представляющий домашний каталог пользователя. exists(Path path, LinkOption. options): проверяет, существует ли файл или каталог, представленный указанным путем. Класс Paths удобен для работы с файловой системой, так как он предоставляет простой и удобный API для работы с путями.

Надо добавить в статью, Paths.get был в 8 Java. Потом появился Path.of. Если у вас не работает Path.of (версия Java не позволяет), только тогда нужен Paths.get

Источник

Оцените статью