This question already has answers here:
Delete directories recursively in Java
(26 answers)
Closed 9 years ago.
Here is a code I tried:
import java.io.*;
public class file03 {
public static void main(String[] args) {
File f1 = new File("C:/tempo1/tempo");
f1.mkdirs();
File f2 = new File("C:/test");
if(!f2.exists()) {
f2.mkdir();
}
f1 = new File("C:/tempo1/kempo");
f1.mkdirs();
f1 = new File("C:/tempo1");
String[] t = {};
if(f1.exists()) {
t = f1.list();
System.out.println(t.length + " files found");
}
for(int i = 0; i < t.length; i++) {
System.out.println(t[i]);
}
try {
Thread.sleep(3000);
}
catch(Exception e) {}
f2.delete();
f2 = new File("C:/tempo1/test.txt");
try {
f2.createNewFile();
}
catch(Exception e) {}
try {
Thread.sleep(7000);
}
catch(Exception e) {}
File f3 = new File("C:/tempo1/renametesting.txt");
f2.renameTo(f3);
try {
Thread.sleep(5000);
}
catch(Exception e) {}
f3 = new File("C:/tempo1");
f3.delete();
}
}
what I noticed was that while the folder test gets deleted, the folder tempo1 doesn't get deleted. Is it because it contains other folders and files? If so, how can I delete it?
I am using BlueJ IDE.
A folder can not be deleted until all files of that folder are deleted.
First delete all files from that folder then delete that folder
This is code for deleting a folder..
You need to pass the path of the folder only
public static void delete(File file)
throws IOException {
if (file.isDirectory()) {
//directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
// System.out.println("Directory is deleted : "+ file.getAbsolutePath());
} else {
//list all the directory contents
String files[] = file.list();
for (String temp : files) {
//construct the file structure
File fileDelete = new File(file, temp);
//recursive delete
delete(fileDelete);
}
//check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
// System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
//if file, then delete it
file.delete();
// System.out.println("File is deleted : " + file.getAbsolutePath());
}
}
public class DeleteFolder {
/**
* Delete a folder and all content folder & files.
* #param folder
*/
public void rmdir(final File folder) {
if (folder.isDirectory()) { //Check if folder file is a real folder
File[] list = folder.listFiles(); //Storing all file name within array
if (list != null) { //Checking list value is null or not to check folder containts atlest one file
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) { //if folder found within folder remove that folder using recursive method
rmdir(tmpF);
}
tmpF.delete(); //else delete file
}
}
if (!folder.delete()) { //if not able to delete folder print message
System.out.println("can't delete folder : " + folder);
}
}
}
}
To delete folder having files , no need of loops or recursive search. You can directly use:
FileUtils.deleteDirectory(<File object of directory>);
This function will delete the folder and all files in it
You can use the commons io library FileUtils class :
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory(java.io.File)
"Deletes a directory recursively."
Related
My problem is not How to make a copy of a File in Android, My problem is why it fails to make a copy.
After my app downloads a file am trying to copy it to another folder (The end user can save the file in several folder, that why i download once and copy to the rest). I do have the origin file path like:
/storage/emulated/0/MyAppFolder/FolderCreatedByUser1/theFile.pdf
And am trying to copy it to
/storage/emulated/0/MyAppFolder/FolderCreatedByUser2/
With this code (Code improved by Robert Nekic):
public static boolean copyFile(File src, File[] dst) {
boolean result = true;
if (src.exists()) {
String srcName = src.getName();
for (File file : dst) {
String to = file.getPath();
try {
File destination = new File(to, srcName);
if (destination.createNewFile()) {
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
dstChnl.transferFrom(srcChnl, 0, srcChnl.size());
srcChnl.close();
dstChnl.close();
} else {
result = false;
System.out.println("Unable to create destination " + destination.getPath());
}
} catch (Exception e) {
result = false;
System.out.println(e.getMessage());
break;
}
}
} else {
result = false;
System.out.println("File " + src.getPath() + " doesn't exist.");
}
return result;
}
The file exist, but am keep getting errors when copying it to the destiny file like:
/storage/emulated/0/MyAppFolder/FolderCreatedByUser2/theFile.pdf: open failed: ENOENT (No such file or directory)
It fails in both streams, when trying to open the src file and/or destination file:
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
Permission to write are granted. The destination folders are created previously to the download of the file, the user can't select a destination if the directory isn't created.
destination = new File(to, srcName); creates a new File instance but does not create the underlying file. You can verify by checking destination.exists(). I believe all you need is:
destination = new File(to, srcName);
destination.createNewFile();
Also, your src path string manipulation and stuff in the first half of your code seems unnecessary and might be introducing an error that could be resolved with something more concise:
public static boolean copyFile(File src, File[] dst) {
boolean result = true;
if (src.exists()) {
String srcName = src.getName();
for (File file : dst) {
String to = file.getPath();
try {
File destination = new File(to, srcName);
if (destination.createNewFile()) {
FileChannel srcChnl = new FileInputStream(src).getChannel();
FileChannel dstChnl = new FileOutputStream(destination).getChannel();
dstChnl.transferFrom(srcChnl, 0, srcChnl.size());
srcChnl.close();
dstChnl.close();
} else {
result = false;
System.out.println("Unable to create destination " + destination.getPath());
}
} catch (Exception e) {
result = false;
System.out.println(e.getMessage());
break;
}
}
} else {
result = false;
System.out.println("File " + src.getPath() + " doesn't exist.");
}
return result;
}
I want to delete file located in local machine, comparing to server machine.
My example :
import java.io.*;
public static void main(String[] args) throws Exception {
Set<String > lmd5 = new HashSet<String>();
lmd5.add("4be1babb2f8cac64d96f8052c0942130");
lmd5.add("a7514d56f233a434c7066176933d708d");
lmd5.add("d41d8cd98f00b204e9800998ecf8427e");
lmd5.add("674e3b94be9ed5db8bafe75808385de1");
Set<String > dmd5 = new HashSet<String>();
dmd5.add("4be1babb2f8cac64d96f8052c0942130");
dmd5.add("a7514d56f233a434c7066176933d708d");
dmd5.add("d41d8cd98f00b204e9800998ecf8427e");
if(lmd5.equals(dmd5)){
System.out.println("OK");
}
else{
lmd5.removeAll(dmd5);
System.out.println("Obsoletes Files To Delete : " + lmd5);
File[] paths = baseModDirectoryFile.listFiles();
for(File path:paths){
FileInputStream fis = new FileInputStream(path);
String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
if(lmd5.contains(md5) ){
File foundFile = path;
System.out.println("Obsolete File Found !");
try{
if(foundFile.delete()){
System.out.println("Obsolete File Deleted !");
}
else{
System.out.println("Obsolete File Not Deleted : Error !");
}
}catch(Exception e){
e.printStackTrace();
}
}
else{
continue;
}
}
}
}
In my output console, I have the message "Obsoletes Files Found" which appears, but after that I have the message : "Obsolete File Not Deleted". I believe I arrive too late in the function to delete the file, as all files have already been checked.
Maybe I have to review this position but I would like to get some advise.
Thank you !
What is the value of foundFile.delete()?
Do you have enough permission to delete file?
May be your file is being locked by your FileInputStream?
I am trying to save contents in file but first I want to search either file does exist or not. But the code I have written, every time it is returning true.
String fileName=FNameTextField.getText();
File file=new File(fileName);
if(file.exists()&& !file.isDirectory()) {
// It returns true if File or directory does exist
System.out.println("the file or directory you are searching does exist : " );
}else{
// It returns true if File or directory not exists
System.out.println("the file or directory you are searching does not exist : " );
}
Thanks.
Your logic seems to be all screwy, or at least I can't make heads or tails of it
if (file.exists()) {
if (file.isDirectory) {
System.out.println("Directory already exists");
} else {
System.out.println("File exists");
}
} else {
System.out.println("Could not find a file or directory matching your request");
}
Try using method...
file.isFile()
The javadoc says
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.
Your logic checks if to see only if it is a file. It will NOT return true if a directory with the name exists as you imply in your print statements.
Make use of this examples which is adopt for you :
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
(or)
import java.io.*;
public class FileChecker {
public static void main(String args[]) {
File f = new File("c:\\mkyong.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
}
}
(or)
import java.io.*;
public class FileOrDirectoryExists{
public static void main(String args[]){
File file=new File("Any file name or
directory whether exists or not");
boolean exists = file.exists();
if (!exists) {
// It returns false if File or directory does not exist
System.out.println("the file or directory
you are searching does not exist : " + exists);
}else{
// It returns true if File or directory exists
System.out.println("the file or
directory you are searching does exist : " + exists);
}
}
}
1. First get all the files in the folder, and store it in an ArrayList.
Eg:
File f = new File("d:\\MyFolder);
File[] fArr = f.listFiles();
ArrayList<File> fList = new ArrayList<File>();
for ( File file : fArr){
if (file.isFile()){
fList.add(file);
}else{
continue;
}
}
2. Now use getName() method to check the file exists or not....
Assume you are looking for a file named "vivek.txt"
Eg:
boolean b = false;
for (File i : fList){
if ((i.getName).equals("vivek.txt")){
b = true;
break;
}
else{
continue;
}
}
The folder I need to delete is one that is created from my program. The directory is not the same on every pc so the folder code I am using is
userprofile+"\\Downloads\\Software_Tokens"
There will be files in, so I guess i need to recursively delete it. I looked at some samples for that here but it never accepts my path. The path works fine in the code as an environmental variable, because i added code for it
static String userprofile = System.getenv("USERPROFILE");
so can someone just show me the code with my path plugged please?
If your directory is not empty, you may use the Apache Commons IO API's method deleteDirectory(File file) :
String toDelete = userprofile + File.separator + "Downloads" +
File.separator + "Software_Tokens";
FileUtils.deleteDirectory(new File(toDelete));
Be careful with the / or \ that are system dependent and use File.separator instead.
If you don't want to use apache library ! You can do it recursively.
String directory = userprofile + File.separator + "Downloads" + File.separator + "Software_Tokens";
if (!directory.exists()) {
System.out.println("Directory does not exist.");
System.exit(0);
} else {
try {
delete(directory);
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Done");
}
public static void delete(File file)
throws IOException {
if (file.isDirectory()) {
//directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
} else {
//list all the directory contents
String files[] = file.list();
for (String temp: files) {
//construct the file structure
File fileDelete = new File(file, temp);
//recursive delete
delete(fileDelete);
}
//check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
//if file, then delete it
file.delete();
System.out.println("File is deleted : " + file.getAbsolutePath());
}
I have this section of code:
public static void delete(File f) throws IOException
{
if (f.isDirectory())
{
for (File c : f.listFiles())
{
delete(c);
}
}
else if (!f.delete())
{
throw new FileNotFoundException("Failed to delete file: " + f);
}
}
public static void traverseDelete(File directory) throws FileNotFoundException, InterruptedException
{
//Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
if (file.getName().equalsIgnoreCase("word"))
{
boolean containsMedia = false;
File[] filesInWordFolder = file.listFiles();
for ( File file2 : filesInWordFolder )
{
if ( file2.getName().contains("media"))
{
containsMedia = true;
break;
}
}
if (containsMedia == false)
{
try
{
delete(file.getParentFile());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
else if (file.isDirectory())
{
traverseDelete(file);
}
}
}
Sorry for the lack of commenting, but it's pretty self-explanatory, I think. Essentially what the code is supposed to do is traverses a set of files in a given directory, if it encounters a directory named "word", then it should list out the contents of word, and then if a directory called "media" does NOT exist, recursively delete everything within the parent directory of "word" down.
My main concern comes from this conditional:
if(!filesInWordFolder.toString().contains("media"))
Is that the correct way to say if the files in that array does not contain an instance of "image", go ahead and delete?
That won't work.
File[] filesInWordFolder = file.listFiles();
if(!filesInWordFolder.toString().contains("media"))
will give you a string representation of a File array -- which will typically have a reference.
You have to iterate through the files to find out if there's any in there that contain the word media.
boolean containsMedia = false;
for ( File file : filesInWordFolder ) {
if ( file.getName().contains("media") ){
containsMedia = true;
break;
}
// now check your boolean
if ( !containsMedia ) {
Well using toString() will give you a String representation of the file (in this case the files). The String representation should contain the file name. If your set purpose is to check for any instance of a file containing the word "media" in the directory, you are fine.
In the example you are printing the String representation of the File array. Instead you should iterate through the File array and check the String representation of each individual File as so:
for (int i = 0; i < file_array.length; i++) {
if ((File)file_array[i]).toString().equals("your_search_term")) {
// The file contains your search term
} else {
// Doesn't contain the search term.
}
}