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);
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();
}
}
Hello all I am using if (canRead && canWrite && !isFloppy && isDrive) and it only will read off the first drive it finds "C:\", I have a HDD and a SSD, it wont detect the ssd for somereason "D:\" for some reason anyehelp? Thanks.
Sorry guys slipped my mind to include the vars:
package javaapplication3;
import java.io.*;
import javax.swing.filechooser.FileSystemView;
class filler
{
public static void main(String ar[]) throws InterruptedException
{
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] f = File.listRoots();
for (int i = 0; i < f.length; i++) {
String drive = f[i].getPath();
String displayName = fsv.getSystemDisplayName(f[i]);
String type = fsv.getSystemTypeDescription(f[i]);
boolean isDrive = fsv.isDrive(f[i]);
boolean isFloppy = fsv.isFloppyDrive(f[i]);
boolean canRead = f[i].canRead();
boolean canWrite = f[i].canWrite();
//(type.toLowerCase().contains("removable") || type.toLowerCase().contains("rimovibile"))
if (canRead && canWrite && !isFloppy && isDrive) {
try {
File file = new File(drive +"log_22_2112321321312.log");
if (file.createNewFile()){
System.out.println("File is created!");
}
if (file.exists()){
System.out.println("Drive found " + drive);
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (canRead && canWrite && !isFloppy && isDrive &&(type.toLowerCase().contains("removable") || type.toLowerCase().contains("rimovibile"))) {
try {
File file = new File("log_22_2112321321312.log");
if (file.createNewFile()){
System.out.println("File is created!");
}
if (file.exists()){
System.out.println("Drive found " + drive);
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Are you using File.listRoots()? Check the output of the following:
File[] roots = File.listRoots();
for (File r : roots)
System.out.println(r);
It's possible that your SSD is being detected but isn't passing your conditional's criteria. Code inside your conditional will only be executed if the specified condition is met. Run your code without the condition to see if the drive isn't actually being recognized, or whether it's not appearing due to a logic error or some other volume setting.
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.
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);
}
}