Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Delete files in a directory

 
bob morkos
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I nned to delete files in a specific directory. Could anyone tell me what's wrong with my code. Thanks.
import java.io.*;
public class FileNav{
public static void main(String argv[]){
//File dir = new File(System.getProperty("user.dir"));
String[] filenames;
String[] files=null;
File f = new File("Download");
filenames = f.list();
for(int i=0; i< filenames.length; i++)
System.out.println(filenames[i]);
File fs= new File(filenames[i]);
fs.delete();
}

}
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by bob, morkos:
I nned to delete files in a specific directory. Could anyone tell me what's wrong with my code. Thanks.
import java.io.*;
public class FileNav{
public static void main(String argv[]){
//File dir = new File(System.getProperty("user.dir"));
String[] filenames;
String[] files=null;
File f = new File("Download");
filenames = f.list();
for(int i=0; i< filenames.length; i++)
System.out.println(filenames[i]);
File fs= new File(filenames[i]);
fs.delete();
}

}

Try with this:
public static void main(String argv[]){
String[] filenames;
String[] files=null;
File f = new File("Download");
filenames = f.list();
for(int i=0; i< filenames.length; i++) { //Don't forget this!!
File fs= new File(f.getName() + File.separator + filenames[i]);
fs.delete();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic