Results 1 to 12 of 12
Like Tree3Likes
  • 1 Post By DarrylBurke
  • 1 Post By simminni
  • 1 Post By abhishekcs86

Thread: class File - delete() - compiles but I don't understand it

  1. #1
    sayswho is offline Member
    Join Date
    Jul 2013
    Location
    Dublin, CA
    Posts
    12
    Rep Power
    0

    Default class File - delete() - compiles but I don't understand it



    Hi, I am trying to learn Java and more specifically I was trying to practice with creating folders and files and reading and writing to/from files.

    Java Code:
    public class createFolder {
    
    	public static void main(String[] args) {
    		
    		try{
    
    		File folder=new File("C:\\TestJava\\TestFolder\\java.txt");
    		boolean fileExists=false;
    	
    		
    		fileExists=folder.exists();
    		
    		System.out.println("File already exists? "+folder.exists());//that's because TO MAKE A FILE USE mkdir()
    		//for nested folders mkdirs
    		
    		String parent=folder.getParent();
    		System.out.println("What is the parent folder? "+parent);
    	fileExists=folder.mkdirs();
    	
    	System.out.println("After using mkdirs - File was created? "+fileExists);//that's because TO MAKE A FILE USE mkdir()
    	//for nested folders mkdirs
    	
    	boolean wasDeleted=folder.delete();// deletes TestFolder but TestJava is still present??
    	System.out.println("After using delete() = File was deleted? "+wasDeleted+ " result is "+ parent);
    		String a = folder.getName();
    		
    		System.out.println("After using getName() "+ a);
    		}
    		
    		catch(Exception e)
    		{
    		  System.out.println ("failed to create"); 
    		}
    	}
    	
    	
    
    }

    Java Code:
    File already exists? false
    What is the parent folder? C:\TestJava\TestFolder
    After using mkdirs - File was created? true
    After using delete() = File was deleted? true result is C:\TestJava\TestFolder
    After using getName() java.txt
    My questions:
    1. why using delete() deletes only the last folder(java.txt)?
    2. how can I delete for example TestFolder and java.txt at the same time?
    3. after I use line 27 and the java.txt is deleted why if I use getName (line 29) I still get java.txt?

    I think I understand about 50% of what is happening in my code..I re- read class File API info like 10 times; read about Path as well..but could someone explain to me what is happening in my code in detail?

    Thank you for your help

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,303
    Rep Power
    20

    Default Re: class File - delete() - compiles but I don't understand it

    Quote Originally Posted by sayswho View Post
    Java Code:
    		File folder=new File("C:\\TestJava\\TestFolder\\java.txt");
    Use meaningful variable names and you won't confuse yourself. Is java.txt a folder?

    Also, there's no need to use (doubled) backslashes in a String literal for a path. Just use the forward slash, which is recognized by all systems.
    Java Code:
    		// File folder=new File("C:\\TestJava\\TestFolder\\java.txt");
    		File file=new File("C:/TestJava/TestFolder/java.txt");
    The value returned by File#getName() is independent of whether the file exists. If it were not so, how would you ever create a new file on disk?

    db
    sayswho likes this.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,303
    Rep Power
    20

    Default Re: class File - delete() - compiles but I don't understand it

    Additionally, class names should start with an uppercase letter. See Code Conventions for the Java Programming Language: Contents

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    simminni's Avatar
    simminni is offline Member
    Join Date
    Jun 2013
    Posts
    4
    Rep Power
    0

    Default Re: class File - delete() - compiles but I don't understand it

    1. why using delete() deletes only the last folder(java.txt)?
    This is pretty much logical. Folder is referencing to a file "java.txt" at location "C:/TestJava/TestFolder/". When you say delete it make sense to delete only the file. Imagine the scenatio of you selecting a file inside a folder and hit delete key. Does it make sense to delete other files or folders or just delete file you selected?

    2. how can I delete for example TestFolder and java.txt at the same time?
    Simple. Point your variable to folder level.

    <CODE>
    import java.io.File;
    class DeleteFolder
    {
    public static void main(String args[])
    {
    File folder=new File("C:\\TestFolder");
    if(folder.exists())
    folder.delete();
    System.out.println(folder.getName());
    }
    }
    </CODE>


    3. after I use line 27 and the java.txt is deleted why if I use getName (line 29) I still get java.txt?
    This is because your folder variable still holds the string value you have passed.
    Last edited by simminni; 07-08-2013 at 09:54 AM. Reason: code tags

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,050
    Rep Power
    6

    Default Re: class File - delete() - compiles but I don't understand it

    Pretty sure that deletion of a folder does not work until the folder is empty on all popular file systems.

  6. #6
    simminni's Avatar
    simminni is offline Member
    Join Date
    Jun 2013
    Posts
    4
    Rep Power
    0

    Default Re: class File - delete() - compiles but I don't understand it

    If the requirement is to delete an empty folder, my above code works. but if the requirement is to delete an folder with files and sub folders you can choose 2 options:

    1. Delete files inside a folder recursively. SampleCode and then delete the folder.
    2. Simply use Apache FileUtils class method deleteDirectory()
    Last edited by simminni; 07-08-2013 at 10:36 AM. Reason: added a statement.
    sayswho likes this.

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,050
    Rep Power
    6

    Default Re: class File - delete() - compiles but I don't understand it

    Indeed. I tend to build in some protection code to not arbitrarily delete just any file or folder.

    - path must be absolute
    - reject deletion of symbolic links and hidden files/directories
    - allow deletion inside the application "working area" only

    Working area is very abstract but in my case it means it is some location or locations that are application specific, usually created by the application itself.

  8. #8
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,568
    Blog Entries
    7
    Rep Power
    21

    Default Re: class File - delete() - compiles but I don't understand it

    I remember that the old 'rm' command in Unix v6 had no notion of absolute or canonical file paths; the code explicitly checked for . or .. (you couldn't do 'rm -rf .' or 'rm -rf ..') but you could easily chop your own head off by doing 'rm -rf ../yourdir/..' ;-)

    kind regards,

    Jos
    Last edited by JosAH; 07-08-2013 at 11:16 AM.
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    abhishekcs86 is offline Member
    Join Date
    Jul 2013
    Location
    Bangalore, India
    Posts
    3
    Rep Power
    0

    Default Re: class File - delete() - compiles but I don't understand it

    Well lets take your questions one by one:

    1. why using delete() deletes only the last folder(java.txt)?
    Well the File.delete() function deletes only the last directory/file specified in the absolute path, in your case which is "C:\TestJava\TestFolder\java.txt"

    2. how can I delete for example TestFolder and java.txt at the same time?
    You can delete only one file/folder using the File.delete() function. Since your file object was pointing to "java.txt" it got deleted. Now if you have to delete the TestFolder as well as Java.txt folder, consider creating a reference to the TestFolder
    Java Code:
    File f = new File("C:\TestJava\TestFolder")
    and then perform delete operation on it. A point to note here is that directories can not be deleted if they are not empty. So what you need is a recursive delete operation. Follow this link to learn how to delete directory in Java.

    3. after I use line 27 and the java.txt is deleted why if I use getName (line 29) I still get java.txt?
    Well you are still getting this because the "folder" variable was pointed to absolute path "C:\\TestJava\\TestFolder\\java.txt" in the beginning of code,
    Java Code:
    File folder=new File("C:\\TestJava\\TestFolder\\java.txt");
    since you did not modify this any where, the complete path is still printed. Note that calling any file operations such as delete() and mkdirs() will not affect the absolute path.


    Hope this helps!! Happy learning!! You can find some good tutorials on Java i/o here.
    sayswho likes this.

  10. #10
    sayswho is offline Member
    Join Date
    Jul 2013
    Location
    Dublin, CA
    Posts
    12
    Rep Power
    0

    Default Re: class File - delete() - compiles but I don't understand it

    Thank you for your answers they were very helpful.
    I guess this is the part where I am confused now:

    Java Code:
    mport java.io.File;
    import java.io.IOException;
    public class PathTesting {
    	public static void main(String [] args) throws IOException {
    		File f = new File("test/.././file.txt");//this is creating a reference to a file
    		f.createNewFile();
    		
    		
    		System.out.println("After using getPath() " +f.getPath());
    		System.out.println("After using getAbsolutePath() " +f.getAbsolutePath());
    		try {
    			System.out.println("After using getCanonicalPath() " + f.getCanonicalPath());
    			boolean isThere=f.exists();
    			System.out.println("does the file exist? " + isThere);//file does not exist yet
    		}
    		catch(Exception e) {}
    	}
    }
    then I get

    Java Code:
    After using getPath() test\..\.\file.txt
    After using getAbsolutePath() C:\Users\inessa\Desktop\WORKING WITH ECLIPSE\practice\test\..\.\file.txt
    After using getCanonicalPath() C:\Users\inessa\Desktop\WORKING WITH ECLIPSE\practice\file.txt
    does the file exist? true
    Somehow it is still nebulous for me or maybe I use them interchangeably when thinking... these 3 Java methods :
    1. relative Path()
    2. absolute Path()
    3. canonical Path()

    and the real absolute Path
    class File - delete()  - compiles but I don't understand it-path.png

    this method :
    1. relative Path() - to put it simply - it turns my path string into an abstract path; and then according to API "An abstract pathname has two components:

    An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the UNIX root directory, or "\\\\" for a Microsoft Windows UNC pathname, and
    A sequence of zero or more string names."
    ..assuming abstract pathname and abstract path have the same meaning..so it just corrects the system dependent prefix string(that's why I can put "//" and it will be converted into "\"), right?

    On line 7, File f = new File("test/.././file.txt") - I am using this constructor-
    "File(String pathname)
    Creates a new File instance by converting the given pathname string into an abstract pathname."

    And then API says "The conversion of a pathname string to or from an abstract pathname is inherently system-dependent." - the way I understand it, I don't really know how it is done but Java converts "test/.././file.txt" into this format:
    "An abstract pathname has two components:

    An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the UNIX root directory, or "\\\\" for a Microsoft Windows UNC pathname, and
    A sequence of zero or more string names."
    Last edited by sayswho; 07-09-2013 at 09:45 AM.

  11. #11
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,653
    Rep Power
    5

    Default Re: class File - delete() - compiles but I don't understand it

    Quote Originally Posted by JosAH View Post
    I remember that the old 'rm' command in Unix v6 had no notion of absolute or canonical file paths; the code explicitly checked for . or .. (you couldn't do 'rm -rf .' or 'rm -rf ..') but you could easily chop your own head off by doing 'rm -rf ../yourdir/..' ;-)
    Unix v6! A blast from the past. I thought I was the only one who remembers that. Our's ran on PDP11/70, PDP/11/45 and and PDP11/34. ca Late 70's early 80's.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  12. #12
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,568
    Blog Entries
    7
    Rep Power
    21

    Default Re: class File - delete() - compiles but I don't understand it

    Quote Originally Posted by jim829 View Post
    Unix v6! A blast from the past. I thought I was the only one who remembers that. Our's ran on PDP11/70, PDP/11/45 and and PDP11/34. ca Late 70's early 80's.
    Those were just before the Vaxen (750, 780) where everthing was a word; those were ideal for Lisp, BCPL and everythiing; we didn't need no steenkin' PCs and Java ;-)

    kind regards,

    Jos (owner of a stone dead PDP/8; those were the days)
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Replies: 5
    Last Post: 07-01-2013, 12:06 PM
  2. Can you help me understand how to use this class.
    By AcousticBruce in forum New To Java
    Replies: 4
    Last Post: 12-30-2010, 03:57 AM
  3. Program compiles but wont run to text file...
    By marylanddem in forum New To Java
    Replies: 2
    Last Post: 12-05-2010, 04:05 PM
  4. Replies: 4
    Last Post: 01-01-2009, 03:58 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •