Java program deleting directories with a JButton - java

I got my program to delete files within a specified file, but then I decided for it to delete the entire directory! This is my code so far, it does nothing when pressing the button... (and the button does have an ActionListener on it).
public void actionPerformed(ActionEvent event) {
if (event.getSource().equals(a)) {
int ans = JOptionPane.showConfirmDialog(null, "You're about to premenently delete this account! Are you sure you want to continue?", "Caution!!", JOptionPane.YES_NO_OPTION);
if (ans == JOptionPane.YES_OPTION){
//delete
File directory = new File("FileIO Plug-Ins\\Accounts\\" + user);
deleteDirectory(directory);
}
run();
}
}
public boolean deleteDirectory(File directory) {
if(directory.exists()){
File[] files = directory.listFiles();
if(files != null){
for(int i = 0; i < files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
System.out.println("deleting: " + files[i].getName());
files[i].delete();
}
}
}
}
return(directory.delete());
}
the for loop I made does indeed find all the files in the specified folder, and the line
System.out.println("deleting: " + files[i].getName());
does also print every file within the 'user' directory, but doesn't delete them. nor does it delete the folder itself.
Please help! any advise or code source would be great!

delete() returns boolean value which you are ignoring.
true - if and only if file or directory was successfully deleted
false - if could not be deleted for some reason
To get the reason, use Files#delete(Path) for deleting the directory, as it gives you exception if the file cannot be deleted due to some reason.
Quoting the JavaDoc for File#delete()
Note that the Files class defines the delete method to throw an
IOException when a file cannot be deleted. This is useful for error
reporting and to diagnose why a file cannot be deleted.

I ran your code in my machine,it's work well.Maybe you don't have permission to delete your target directory.You can test with my code to find out which file's delete operation is failed.
public static boolean deleteDirectory(File directory) {
if(directory.exists()){
File[] files = directory.listFiles();
if(files != null){
for(int i = 0; i < files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
if(files[i].delete()) {
System.out.println("Successfully delete: " + files[i].getAbsolutePath());
} else {
System.out.println("Failed to delete: " + files[i].getAbsolutePath());
return false;
}
}
}
}
}
if(directory.delete()){
System.out.println("Successfully delete: " + directory.getAbsolutePath());
return true;
} else {
System.out.println("Failed to delete: " + directory.getAbsolutePath());
return false;
}
}

Related

Java program, int i (i=0) default value is being used despite it increasing by 1 each loop

I am creating a JAVA program to copy certain folders to a new location automatically, to do this I created a function with a loop to use the same function for each given folder source and destination. The problem is that the function will just copy the first folder to the new location multiple times instead of copying it once then copying the next folder. The folder locations are held in a string array and a specific one is selected by changing value [i]. Each time the function loops [i] increases but the loop does not select the [i] value as well as the next folder to copy.
Is anyone able to help me with this, the code i am working with is below, Thanks.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Application {
static String[] saves = {
"C:\\Users\\Lucas\\Documents\\My Games\\Halo",
"C:\\Users\\Lucas\\Documents\\My Games\\Terraria",
"C:\\Users\\Lucas\\Documents\\My Games\\Borderlands 2",
"C:\\Users\\Lucas\\Documents\\My Games\\Rocket League"
};
private static int i = 1;
File source = new File(saves[i]);
static File folder = new File("Saves\\");
File dest = new File(String.valueOf(folder) + "\\" + source.getName());
private void Start() throws IOException {
MakeDirectory(folder);
Copy();
}
private void Copy() throws IOException {
copyFileUsingJava7Files(source, dest);
Add();
}
private void Add() throws IOException {
i++;
System.out.println("Value of i = " + i);
System.out.println("");
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
if (!dest.exists()) {
System.out.println("Copying files from: " + "'" + source + "'");
System.out.println("");
copyFolder(source, dest);
System.out.println("File copied");
} else {
copyFolder(source, dest);
}
}
private static void copyFolder(File source, File dest) throws IOException {
if (source.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory created :: " + dest);
}
String files[] = source.list();
for (String file : files) {
File srcFile = new File(source, file);
File destFile = new File(dest, file);
copyFolder(srcFile, destFile);
}
} else {
if (source.lastModified() > dest.lastModified()) {
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied :: " + dest);
} else {
System.out.println("A newer version exists of: " + "'" + dest + "'");
}
}
}
private static void MakeDirectory(File folder) {
if (!folder.exists()) {
System.out.println("Creating directory: " + "'" + folder + "'");
folder.mkdir();
System.out.println("Directory created");
} else {
System.out.println("Directory already exists: " + "'" + folder + "'");
}
}
public static void main(String[] args) throws IOException {
Application app = new Application();
int l;
for (l = 0; l < 3; l++) {
app.Start();
}
}
}
It doesn't look like you're ever changing the source field after setting it initially. You're setting it to the second file, but then not changing it later. Incrementing i won't automatically update source because source is just a File.
Also, you're starting with i = 1. In Java, arrays are zero-indexed, which means that the first item in the array is actually item 0, so you should be starting with i = 0 instead.
You have to reinitialize File source each time, you increase i. Otherwise, the source won't be changed.
Since i is a static variable, all objects share the same variable. Since you are incrementing the i during each app.Start() method, at the end of calling 5 times, its value is 5. Consequently you get the output as 5 in all your sys outs. Thats the point of static.

How to rename file java ?

I'm trying to rename files in a folder. But instead all of them get deleted
File thisFolder = new File("C:\\ . . . ");
File [] filesArray = thisFolder.listFiles();
int filesArrayLength = filesArray.length;
if (filesArray != null) {
for (int i = 0; i < filesArrayLength; i++) {
filesArray[i].renameTo(new File("test" + i + ".pdf"));
}
}
What am i doing wrong ? Why do all of the files get deleted instead of renamed
As #Pshemo pointed out you might be moving the file to the current directory. Try doing this instead. This will tell it to create the file under the given parent directory:
filesArray[i].renameTo(new File(thisFolder, "test" + i + ".pdf"));//thisFolder is your parent directory
String strFilePath= "C:/Users/";
public void renameFile(String strOldFileName, String strNewFileName) {
File oldName = new File(strFilePath + "/" + strOldFileName);
File newName = new File(strFilePath + "/" + strNewFileName);
if (oldName.renameTo(newName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
Code example for you to rename the List of files in a given directory as below,
Suppose C:\Test\FileToRename isthe folder, the files which are listed under that has been renamed to test1.pdf,test2.pdf... etc..
File folder = new File("\\Test\\FileToRename");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
File f = new File("c:\\Test\\FileToRename\\"+listOfFiles[i].getName());
f.renameTo(new File("c:\\Test\\FileToRename\\"+"test"+i+".pdf"));
}
}

Java - Delete folder and its contents

I've got the following code to delete a folder and its contents but its only deleting the contents and not the folder. How can i change it to delete the folder as well?
private static void deleteCat(String catName) {
File fileToDel = new File("Catalogues/" + catName);
if (fileToDel.exists()) {
if (fileToDel.isDirectory()) {
if (fileToDel.list().length > 0) {
for (String s : fileToDel.list()) {
deleteCat(catName + "/" + s);
}
}
} else {
if (fileToDel.delete()) {
System.out.println("File " + fileToDel + " deleted");
} else {
System.out.println("Unable To Del " + fileToDel);
}
}
}
}
remove the else of line 10. fileToDel.delete() must be executed anycase.
When you're trying to delete a directory, you've not included the code to delete the directory itself
private static void deleteCat(String catName) {
File fileToDel = new File("Catalogues/" + catName);
if (fileToDel.exists()) {
if (fileToDel.isDirectory()) {
if (fileToDel.list().length > 0) {
for (String s : fileToDel.list()) {
deleteCat(catName + "/" + s);
}
}
fileToDel.delete();
}
//Always want to delete the given file, so remove the 'else'
if (fileToDel.delete()) {
System.out.println("File " + fileToDel + " deleted");
} else {
System.out.println("Unable To Del " + fileToDel);
}
}
}
It deletes only your content, because you don't delete the directories. Add at the end of your directoryroutine the command to delete your directory too.
if (fileToDel.isDirectory()) {
if (fileToDel.list().length > 0) {
for (String s : fileToDel.list()) {
deleteCat(catName + "/" + s);
}
}
fileToDel.delete(); //delete directory
} else ...
Also have a look at the apache commons-io lib (http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory(java.io.File))

See the list of the files in an external storage

I wanted to see all the files I have in my external storage, I have this library that display the text to the user, but when I'm using it to show the sub files, it says something like :
(Ljava.File;# How do I get it to show the name of the actual files to the user? Also, how can I show the name for a specific folder to the user? say file #3?
File[] files = myDir.listFiles();
UIHelper.displayText(this, R.id.textView1, files.toString());
Checl if sdcard is mounted or not.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
///mounted
}
Get the path of sd card
File dir= new File(android.os.Environment.getExternalStorageDirectory());
Then call
walkdir(dir);
ArrayList<String> filepath= new ArrayList<String>();//contains list of all files ending with
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {// if its a directory need to get the files under that directory
walkdir(listFile[i]);
} else {// add path of files to your arraylist for later use
//Do what ever u want
filepath.add( listFile[i].getAbsolutePath());
}
}
}
}
This is the code for printing list of files and folders from ExternalStorage
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
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++)
{
Log.d("Files", "FileName:" + file[i].getName());
}
Don't forget to put below permission in you android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can use a recursive method to scan all your SD card:
String sdCardState = Environment.getExternalStorageState();
if( !sdCardState.equals(Environment.MEDIA_MOUNTED ) ) {
//displayMessage("No SD Card.");
return;
} else {
File root = Environment.getExternalStorageDirectory();
lookForFilesAndDirectories(root);
}
// lookForFilesAndDirectories() method:
public void lookForFilesAndDirectories(File file) {
if( file.isDirectory() ) {
String[] filesAndDirectories = dir.list();
for( String fileOrDirectory : filesAndDirectories) {
File f = new File(dir.getAbsolutePath() + "/" + fileOrDirectory);
lookForFilesAndDirectories(f);
}
} else {
doSomethingWithFile(f);
}
}

Prevent Dir deleting

the following code is deleting files and DIRS in a specific folder.
How could I adjust it, so it will delete only the files in the folder but not the dirs inside
code:
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (int i = 0; i < listOfFiles.length; i++)
{
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
}
thanks,
ray.
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (int i = 0; i < listOfFiles.length; i++)
{
if( !listOfFiles[i].isDirectory() ){ // if not a directory...
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
}
}
Make sense? :)
Easy ...
if (!listOfFiles[i].isDirectory()) {
listOfFiles[i].delete();
}
FWIW - your current code will only delete empty subdirectories. According to the javadoc, deleting a directory that is non-empty will fail; i.e. return false.
You have to use File.isDirectory
if(!listOfFiles[i].isDirectory())
{
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
http://download.oracle.com/javase/6/docs/api/java/io/File.html#isDirectory()
if (!listOfFiles[i].isDirectory()) { listOfFiles[i].delete(); }

Categories

Resources