Java deleting folder and sub-folder 4th level - java

I want delete folder (directory) and sub-directory in JAVA, I need 2 conditions when there's file and where the folder is empty. I've been searched and trying all example I found, but not worked. Even when that code works, that just delete the file or just 1 folder (directory level 4) not all folder.
I want to delete old directory year\place\owner\month\file.
File source = new File("C:\\Users\\Workspaces\\projects\\uploadFolder\\year\\place\\owner\\month\\file");
Path sources = source.toPath();
I've tried this:
public static void rmdir(final File folder) {
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null){
for (int i = 0; i < list.length; i++){
File tmpF = list[i];
if (tmpF.isDirectory()) {
rmdir(tmpF); }
tmpF.delete();}
}
if (!folder.delete()){
System.out.println("can't delete folder : " + folder);}}
}
This:
public static void deleteDirectory(File path)
{
if (path == null)
return;
if (path.exists())
{
for(File f : path.listFiles())
{
if(f.isDirectory())
{
deleteDirectory(f);
f.delete();
}
else
{
f.delete();
}
}
path.delete();
}
}
This :
public static void deleteFiles (File file)
{
if(file.isDirectory())
{
File[] files = file.listFiles(); //All files and sub folders
for(int x=0; files != null && x<files.length; x++)
deleteFiles(files[x]);
file.delete();
}
}
This:
FileUtils.deleteDirectory(source);
This:
Files.delete(sources);

Related

I want to delete a folder,but,i just delete the last one file in the folder

I want to delete a folder that has some other files. First, I'll delete all files in the folder, but I just delete the last file, and I cannot delete the folder.
This is my code:
private void deleteFiles(File file) {
if (file.isDirectory()) {
String [] files = file.list();
for (int i= 0 ; i < files.length ; i++) {
deleteFiles(new File(file, files[i]));
}
}
file.delete();
}
private String deleteFile (File file){
String info = "";
if(file.isFile()){
if(file.delete()){
info = "remove file success";
}
}else if(file.isDirectory()){
File[] files = file.listFiles();
for(int i = 0;i < files.length;i++){
this.deleteFile(files[i]); //recursion
}
file.delete();
info = "remove folder success";
}else{
info = "not exist";
}
return info;
}

Rename all folders in a directory

I need help in renaming all files and folders in a directory and add a character in front of there original name.
This is a method to rename a single folder:
File from = new File(sdcard,".DCIM");
File to = new File(sdcard,"DCIM");
from.renameTo(to);
So, something like:
String path = Environment.getExternalStorageDirectory().toString()+"/MyDir";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
file[i].renameTo(file[i].getName() + "x");
}
EDIT:
To change a file name, it might be more clear to add a temporary variable:
String name = file[i].getName();
name = name.substr(0, name.length() - 1);
file[i].renameTo(name);
Go to the root folder and iterate over it. Just check if the the folder you are accessing is a directory or not and you can write the same logic in between for every folder.
public static void renameFile(String path) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
if (list == null)
return;
for (File f : list) {
if (f.isDirectory()) {
File from = new File(f,"."+f.getName());
File to = new File(f,f.getName());
from.renameTo(to);
renameFile(f.getCanonicalPath());
} else {
System.out.println("File:" + f.getAbsoluteFile());
}
}
}
public static void main(String[] args) throws IOException {
//Root path within which you want to change the folder names
renameFile("c:\rootPath");
}
Just check if this helps you.

Deleting Files and Directories not working

I am trying to delete all the files inside a directory then the directory afterwards using the below code but it doesn't seem to work. (Files are not deleted after the method ran).
public void DeleteDirectory() {
ArrayList<File> Directories = new ArrayList<File>();
Directories.add(new File(Environment.getExternalStorageDirectory().toString().concat("/AssetControl/Images")));
Directories.add(new File(Environment.getExternalStorageDirectory().toString().concat("/AssetControl/Thumbnails")));
ListIterator<File> itr = Directories.listIterator();
while (itr.hasNext()) {
File dir = itr.next();
if (dir.isDirectory()) {
String[] files = dir.list();
for (int i = 0; i < files.length; i++) {
(new File(files[i])).delete();
// This is also not working:
// File current = new File(files[i]);
// current.delete();
}
dir.delete();
}
}
}
This worked for me:
replaced String[] files with File[] files.
while (itr.hasNext()) {
File dir = itr.next();
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
DeleteFile(files[i]);
}
dir.delete();
}
}

Reading all files in a directory including its sub directories

This is how I set the path:
dPath = dPath.replace("\\", "/");
String iLen;
String FileName;
File iFolder = new File(dPath);
File[] listOfFiles = iFolder.listFiles();
When searching:
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
FileName = listOfFiles[i].getName();
for(String s : iEndsWith)
{
if(FileName.toLowerCase().endsWith(s))
{
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy h:mm aaa");
iLen = ReadableBytes(listOfFiles[i].length());
Object rowData[] = { FileName, listOfFiles[i].getAbsoluteFile(), sdf.format(listOfFiles[i].lastModified()), iLen };
iTableModel.addRow(rowData);
iTotalFiles ++;
}
}
}
}
That will only look for files in the given directory path, but not it's sub directories. How can I change that?
If you're on Java 7, you can use FileVisitor: http://docs.oracle.com/javase/tutorial/essential/io/walk.html
If not, just use a simple recursive version of your function.
Pass folder as Initial File which is to be searched
File foldr = new File("c:/javaFolder");
public void addFilesToList(File folder) {
File[] listofFiles = folder.listFiles();
if (listofFiles != null) {
for (File file : listofFiles) {
if (file.isFile()) {
} else
addFilesToList(file);
}
}
}
You can use DirectoryWalker from Apache Commons to walk through a directory hierarchy.

get number of files in a directory and its subdirectories

using this code
new File("/mnt/sdcard/folder").listFiles().length
returns a sum of folders and files in a particular directory without caring about subdirectories.
I want to get number of all files in a directory and its subdirectories.
P.S. : hardly matters if it returns a sum of all the files and folders.
any help appreciated,
thanks
Try this.
int count = 0;
getFile("/mnt/sdcard/folder/");
private void getFile(String dirPath) {
File f = new File(dirPath);
File[] files = f.listFiles();
if (files != null)
for (int i = 0; i < files.length; i++) {
count++;
File file = files[i];
if (file.isDirectory()) {
getFile(file.getAbsolutePath());
}
}
}
It may help you.
You can use recursion.
public static int getFilesCount(File file) {
File[] files = file.listFiles();
int count = 0;
for (File f : files)
if (f.isDirectory())
count += getFilesCount(f);
else
count++;
return count;
}
Using Java 8 NIO:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public long fileCount(Path dir) {
return Files.walk(dir)
.parallel()
.filter(p -> !p.toFile().isDirectory())
.count();
}
public void main(String... args) {
Path dir = Paths.get(args[0]);
long count = fileCount(dir);
System.out.println(args[0] + " has " + count + " files");
}
}
public Integer countFiles(File folder, Integer count) {
File[] files = folder.listFiles();
for (File file: files) {
if (file.isFile()) {
count++;
} else {
countFiles(file, count);
}
}
return count;
}
Usage:
Integer count = countFiles(new File("your/path"), Integer.valuOf(0));
you will have to do a recursive search over your files.
Use `File#isDrirectory()ยด to check if a file is a directory and traverse the file tree down.
You have to go though all the folder recursively and find out the files
int mCount;
getTotalFiles(File dir) {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
getTotalFiles(file);
} else {
mCount++;
}
}
}
Something I've used before, you can easily edit it to get what you want:
public class Filewalker {
public void walk( String path ) {
File root = new File( path );
File[] list = root.listFiles();
for ( File f : list ) {
if ( f.isDirectory() ) {
walk( f.getAbsolutePath() );
System.out.println( "Dir:" + f.getAbsoluteFile() );
}
else {
System.out.println( "File:" + f.getAbsoluteFile() );
}
}
}
public static void main(String[] args) {
Filewalker fw = new Filewalker();
fw.walk("c:\\" );
}
}
Here's a short one all encapsulated within a single method just returning the number of files and directories within a specific directory:
public static int countFiles(File directory) {
int count = 0;
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
count += countFiles(file);
}
count++;
}
return count;
}
Cheers!
Just for the record, you may also use iteration instead of recursion:
public static int countFiles(final File dir) {
final ArrayDeque<File> dirs = new ArrayDeque<>();
dirs.add(dir);
int cnt = 0;
while (!dirs.isEmpty()) {
final File[] files = dirs.poll().listFiles();
for (final File f: files)
if (f.isDirectory())
dirs.add(f);
else
++cnt;
}
return cnt;
}
In this implementation I'm using ArrayDeque but you can use any Queue or any List for the job.
public int numberOfFiles(File srcDir) {
int count = 0;
File[] listFiles = srcDir.listFiles();
for(int i = 0; i < listFiles.length; i++){
if (listFiles[i].isDirectory()) {
count += numberOfFiles(listFiles[i]);
} else if (listFiles[i].isFile()) {
count++;
}
}
return count;
}
http://www.java2s.com/Code/Java/File-Input-Output/Countfilesinadirectoryincludingfilesinallsubdirectories.htm
public static int countFilesInDirectory(File directory) {
int count = 0;
for (File file : directory.listFiles()) {
if (file.isFile()) {
count++;
}
if (file.isDirectory()) {
count += countFilesInDirectory(file);
}
}
return count;
}
refer this site
it gives perfect answer
import java.io.File;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Path for Directory/Folder Name");
String Directory=sc.nextLine();
System.out.println("Your Directory/folder is :"+Directory);
File f = new File(Directory);
int countFiles = 0;
int countDirectory=0;
for (File file : f.listFiles()) {
if (file.isFile()) {
countFiles++;
}
if (file.isDirectory()) {
countDirectory++;
}
}
System.out.println("Number of files in Directory : " + countFiles+"\nNumber of Sub-directories "+countDirectory);
}
}

Categories

Resources