Results 1 to 8 of 8
  1. #1
    achilles is offline Member
    Join Date
    Aug 2009
    Posts
    5
    Rep Power
    0

    Unhappy Checking if file exists in a directory

    Hey everyone!

    I am new to Java. I'm trying to write a program, which creates a new file on each run. If a file with the same name exists in the current directory, it should change the name of the new file to avoid replacing the old files.
    Here's the code I've written to do this:

    PHP Code:
    Random rand = new Random((long)Math.random());
    String filename ="myout"+rand.nextInt();
    String path = "/home/achilles/input";
    
    try{
        File file = new File(filename);
        File directory = new File(path);
        File[] listOfFiles= directory.listFiles();
    								
    	if (!file.createNewFile()) {
    	    System.out.println("File Name: "+file + " --Exists!!!");
    	    System.out.println("File Name for file.getName(): "+file.getName());
    	    System.out.println("File Name for filename: "+filename);
    
                for (File f: listOfFiles) {
      	       	 System.out.println("About to Compare: "+filename+" : "+f.getName());
    	              if(f.getName() == filename)	{
    		             filename +=rand.nextInt();
    		             System.out.println("Found one! = "+filename);
    		}
    	 }
    
    	System.out.println("New File Name: "+filename);
    	}
    }
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(path+"/"+filename)));
    out.close();

    But even when it finds two files with the same name, the if(f.getName() ==filename) condition is still not evaluated to true and that code is never executed.
    I can't figure out what is wrong with the code.

    Any help would be highly appreciated.

    Thanks.

    EDIT:
    A quick edit and added this line in the foreach loop:
    System.out.println(filename == f.getName());
    but it always returns false! even when :
    filename = myout-1155484576
    f.getName() = myout-1155484576


    EDIT2:
    Solved :p I didn't realize that I was using == to for comparing strings !
    Last edited by achilles; 08-09-2009 at 05:19 AM. Reason: minor addition

  2. #2
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    Java Code:
    if(f.getName() == filename)    {
    try equals()
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  3. #3
    achilles is offline Member
    Join Date
    Aug 2009
    Posts
    5
    Rep Power
    0

    Default

    Yes, thank you very much... I just realised that ;d

  4. #4
    achilles is offline Member
    Join Date
    Aug 2009
    Posts
    5
    Rep Power
    0

    Default

    There's still a slight problem with the logic. If it finds a duplicate file... it will try to append nextInt to the end of current filename and move ahead, but what if the new filename conflicts with an already compared file? In that case the old file would be replaced.

    Any ideas how to avoid this?

  5. #5
    corlettk is offline Member
    Join Date
    Apr 2009
    Location
    Brisbane
    Posts
    86
    Rep Power
    0

    Default

    Quote Originally Posted by achilles View Post
    what if the new filename conflicts with an already compared file?
    Java Code:
    package forums;
    
    import java.io.File;
    import java.util.Random;
    
    class FileUtils
    {
      private static final Random random = new Random();
    
      public static File uniqueFile(String prefix, String suffix) {
        File uniqueFile = null;
        for(int i=1; i<1000; i++) {
          File file = new File(prefix + i + suffix);
          if ( !file.exists() ) {
            uniqueFile = file;
            break;
          }
        }
        return uniqueFile;
      }
    
      // test harness
      public static void main(String[] args) {
        try {
          String outputFilename = "C:/tmp/myout"+random.nextInt();
          File uniqueFile = uniqueFile(outputFilename, ".txt");
          if (uniqueFile==null) {
            System.out.println("Can't create unique filename for: "+outputFilename);
          } else {
            System.out.println("unique filename: "+uniqueFile.getAbsoluteFile());
          }
        } catch (Exception e) {
          System.err.println("Failed to create unique filename for: "+outputFilename);
          e.printStackTrace();
        }
      }
    
    }

  6. #6
    achilles is offline Member
    Join Date
    Aug 2009
    Posts
    5
    Rep Power
    0

    Default

    Correct me if I'm wrong but I think there is still a probability of over-writing a file that already exists. If you instrument the code a little and make it look like this:

    Java Code:
    
    package test;
    
    import java.util.Random;
    import java.io.File;
    
    public class FileUtils {
    	
    	  private static final Random random = new Random();
    
    	  public static File uniqueFile(String prefix, String suffix) {
    	    File uniqueFile = null;
    	    System.out.println("Filename received: "+prefix+suffix);
    	    for(int i=1; i<1000; i++) {
    	      File file = new File(prefix + i + suffix);
    	      if ( !file.exists() ) {
                    System.out.println("File does not exist: "+file );
    	        uniqueFile = file;
    	        break;
    	      }
    	      
    	      
    	    }
    	    return uniqueFile;
    	  }
    
    	  // test harness
    	  public static void main(String[] args) {
    		    
    		    for(int i=0; i<100; i++){
    		    	String outputFilename = "/home/user/input"+random.nextInt(10);
    		  try {
    			  
    	  	      File uniqueFile = uniqueFile(outputFilename, ".txt");
    	  	    System.out.println("returned: "+uniqueFile);
    	      if (uniqueFile==null) {
    	        System.out.println("Can't create unique filename for: "+outputFilename);
    	      } else {
    	        System.out.println("unique filename: "+uniqueFile.getAbsoluteFile());
    	      }
    	      System.out.println("-----------------------------------------------");
    	    } catch (Exception e) {
    	      System.err.println("Failed to create unique filename for: "+outputFilename);
    	      e.printStackTrace();
    	    }
    		    }
    	  }
    
    	
    
    }
    This is the output you get:
    Java Code:
    -----------------------------------------------
    Filename received: /home/user/input4.txt
    File does not exist: /home/user/input41.txt
    returned: /home/user/input41.txt
    unique filename: /home/user/input41.txt
    -----------------------------------------------
    Filename received: /home/user/input3.txt
    File does not exist: /home/user/input31.txt
    returned: /home/user/input31.txt
    unique filename: /home/user/input31.txt
    -----------------------------------------------
    Filename received: /home/user/input7.txt
    File does not exist: /home/user/input71.txt
    returned: /home/user/input71.txt
    unique filename: /home/user/input71.txt
    -----------------------------------------------
    Filename received: /home/user/input3.txt
    File does not exist: /home/user/input31.txt
    returned: /home/user/input31.txt
    unique filename: /home/user/input31.txt
    -----------------------------------------------
    Filename received: /home/user/input0.txt
    File does not exist: /home/user/input01.txt
    returned: /home/user/input01.txt
    unique filename: /home/user/input01.txt
    -----------------------------------------------
    Filename received: /home/user/input0.txt
    File does not exist: /home/user/input01.txt
    returned: /home/user/input01.txt
    unique filename: /home/user/input01.txt
    -----------------------------------------------
    Filename received: /home/user/input3.txt
    File does not exist: /home/user/input31.txt
    returned: /home/user/input31.txt
    unique filename: /home/user/input31.txt
    -----------------------------------------------
    Filename received: /home/user/input7.txt
    File does not exist: /home/user/input71.txt
    returned: /home/user/input71.txt
    unique filename: /home/user/input71.txt
    -----------------------------------------------
    Filename received: /home/user/input1.txt
    File does not exist: /home/user/input11.txt
    returned: /home/user/input11.txt
    unique filename: /home/user/input11.txt
    -----------------------------------------------
    Filename received: /home/user/input4.txt
    File does not exist: /home/user/input41.txt
    returned: /home/user/input41.txt
    unique filename: /home/user/input41.txt
    -----------------------------------------------
    Filename received: /home/user/input9.txt
    File does not exist: /home/user/input91.txt
    returned: /home/user/input91.txt
    unique filename: /home/user/input91.txt
    -----------------------------------------------
    Filename received: /home/user/input2.txt
    File does not exist: /home/user/input21.txt
    returned: /home/user/input21.txt
    unique filename: /home/user/input21.txt
    -----------------------------------------------
    Filename received: /home/user/input3.txt
    File does not exist: /home/user/input31.txt
    returned: /home/user/input31.txt
    unique filename: /home/user/input31.txt
    -----------------------------------------------
    Filename received: /home/user/input6.txt
    File does not exist: /home/user/input61.txt
    returned: /home/user/input61.txt
    unique filename: /home/user/input61.txt
    -----------------------------------------------
    Filename received: /home/user/input5.txt
    File does not exist: /home/user/input51.txt
    returned: /home/user/input51.txt
    unique filename: /home/user/input51.txt
    -----------------------------------------------

  7. #7
    angryboy's Avatar
    angryboy is offline Senior Member
    Join Date
    Jan 2009
    Posts
    742
    Rep Power
    6

    Default

    If you want unique filename, just do this:
    Java Code:
          String outputFilename ="myout";
          String path = "/home/achilles/input";
          File uniqueFile = File.createTempFile(outputFilename, ".txt", path);
    it'll create a file "myout1234" where 1234 is random.
    USE CODE TAGS--> [CODE]...[/CODE]
    Get NotePad++ (free)

  8. #8
    achilles is offline Member
    Join Date
    Aug 2009
    Posts
    5
    Rep Power
    0

    Default

    That's exactly the solution I was looking for ;d Thanks a million angryboy!

Similar Threads

  1. reading an Html file and checking for urls
    By sudukrish in forum Advanced Java
    Replies: 1
    Last Post: 04-25-2009, 01:39 AM
  2. Replies: 2
    Last Post: 04-07-2009, 06:25 AM
  3. [SOLVED] File chooser selecting file from directory...?
    By prabhurangan in forum AWT / Swing
    Replies: 12
    Last Post: 06-18-2008, 04:08 AM
  4. How to check whether file is exists or not
    By Java Tip in forum java.io
    Replies: 0
    Last Post: 04-05-2008, 10:13 AM
  5. Checking of file was modified on the server
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-02-2008, 07:18 PM

Posting Permissions

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