Hello all!

I'm working on setting up a program to go about some files in a directory, do with them what I need, then delete. So, I started with the unfamiliar part for me, as the rest I am sure will be easy as pie. I tried to just write a small program that would delete all the files for me in a given, static folder. Here is what I have as the code:

import java.lang.*;
import java.io.*;

public class FileDeletes {
public static void main (String args[])
{
	File dir = new File("C:\\Test");
	String[] children = dir.list();
	String temp;
	System.out.println("First is "+children[0]+" !");
	for (int i=0; i<children.length; i++)
	{
		temp=children[i].toString();
		System.out.println("Its "+temp+" !");
		File inuse = new File(temp);
		boolean success =	inuse.delete();
		if (success)
			System.out.println("Success");
		else
			System.out.println("Failed");
	}
}
}

I added a few checks to ensure my variable is not null, in the form of some system.outs. They always reply with the name of the file correctly, the loop will get me the names of all files, but then the delete ALWAYS fails. Now, if i replace the part:

File inuse = new File(temp)

with

File inuse = new File("TextFile.txt")

it works no problem! I have also tried to skip the temp toString() function and just used children to delete the files, but it doesn't work either. It seems logically its all correct, but I just cannot see why the delete fails.

Any suggestions?

like that it will not set the file path correctly.
so instead of
File inuse = new File(temp)
you need to write
File inuse = new File("c:\\test\\"+temp)

cheers

like that it will not set the file path correctly.
so instead of
File inuse = new File(temp)
you need to write
File inuse = new File("c:\\test\\"+temp)
cheers

vchandra is right.

Also it is a good thing always to check the API of the classes you are using. Why did you assumed that the dir.list() method returns what you want. If you had looked the API you would have seen that it doesn't return the full path.
You could also see this other method that does what you want:

File [] children = dir.listFiles();

You could have used that instead that returns the full path of the file.

Also whenever you are having problems you can print the values of what you are using:

// -->
System.out.println("Deleting: "+inuse);

boolean success =	inuse.delete();

You would have seen that the "inuse" file is not the right file.

Ah, very prefect, thanks.

Good point on looking a bit more into this instead of assuming I was getting what I wanted. Def gonna keep that in mind for future work, but now with this I've got my fully functioning program, thanks!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.