0

I'm trying to delete a file, but it wont be deleted. If I run it as "gui", it's ok while when I run it with command line (String[] args) the file cannot be deleted. When I debug it, the file can be removed, and when I run the program the file is not deleted..why?

When I run it as a "gui" everything is fine, but my problem happens when I run it with "String[] args".

This is the part that not working:

fis.close();
File file = new File((Target_Folder_Name + "\\" + Target_Filename + ".txt"));
file.delete();
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • probably you are not escaping correctly the arguments you pass to you application through command line. Send the code you use else we cannot help you. – piacente.cristian Feb 28 '14 at 14:00
  • First things first: do you use Java 7? – fge Feb 28 '14 at 14:00
  • 1
    Write the filename on `stdout` and check whether it's the same. You probably use relative filenames and start the JVM from a different folder. – Axel Feb 28 '14 at 14:02
  • i think i'm using Java 7, yes. – user3365058 Feb 28 '14 at 14:02
  • i added this code: boolean succses = file.delete(); System.out.print(succses); – user3365058 Feb 28 '14 at 14:05
  • In this case, don't use `File` anymore: use the new Files API. `Files.delete(Paths.get(Target_Folder_Name).resolve(Target_Filename + ".txt"));` <-- big advantage over `File.delete()`: throws a meaningful exception if it fails! – fge Feb 28 '14 at 14:06
  • Eh, OK, but that was pure chance; I don't see why your original attempt failed, but ohwell... Anyway, drop `File`. Starting with Java 7, it makes no sense at all to use it anymore. – fge Feb 28 '14 at 14:11
  • can you please add it as an answer, because i want to make " V " on it? – user3365058 Feb 28 '14 at 14:19
  • @fge File still makes sense when the file is marked as read-only on Windows because Files.delete [will not work](http://stackoverflow.com/q/12139482/3080094) in that case. You have to remove the read-only (and hidden) attribute before the file can be deleted which is not easy using the new Java 7 Files API (in fact, it is a real hassle). – vanOekel Feb 28 '14 at 17:03
  • @vanOekel I have read the link and personally consider this to be a bug in `File`; I certainly do NOT want the JVM to modify file attributes behind my back... @user3365058: my proposal was pure luck; I fail to see why it worked whereas your solution didn't, as such I do not consider it an answer ;) – fge Feb 28 '14 at 17:52
  • @fge anyway, i do appreciate your help :-) – user3365058 Mar 01 '14 at 12:05

0 Answers0