#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    93
    Rep Power
    26

    Determining whether a user entered string is a relative or an absolute path


    Hey guys.

    I am writing a small program that needs to determine whether a user entered string is a relative path or an absolute path. Basically, what I am trying to do in pseudo-code is...

    Code:
    private static boolean isRelative(String path) {
        //return true if the path is relative, false if it is absolute
    }
    
    ...
    
    String path = getUserEnteredPath();
    if ( isRelative(path) ) {
         //append an environment variable to the path before we use it
    } else {
         //utilize the path in its current form
    }
    ...

    The part I am struggling with is the best way to write the isRelative method. I was thinking about using a regular expression on the first three characters against "[A-Z]:\", but there are a few things I don't like about that approach. For one, it will only work on Windows, which is acceptable but not ideal. Second, I don't know how to use regular expressions and would just as soon avoid doing so if I can get by without it.

    What do you guys think, is there a better way?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    93
    Rep Power
    26
    Here's another method of determining relative or absolute paths I came up with. I like it better than using regular expressions since it is platform independent, but I am still open to suggestions if anyone thinks there is a better way.

    Code:
    	private static String formatPath( String p ) {
    		
    		File absoluteFile = null;
    		File relativeFile = null;
    		
    		
    		absoluteFile = new File(p);
    		
    		String relativeFileName = ENV_VAR + SEP_CHAR + p;
    		relativeFile = new File(relativeFileName);
    		
    		String path = "";
    		
    		if (absoluteFile.exists()) {
    			//TODO use absolute file path
    			path = absoluteFile.getAbsolutePath();
    			System.out.println("Absolute: " + path);
    		} else if (relativeFile.exists()) {
    			//TODO use relative file path
    			path = relativeFile.getAbsolutePath();
    			System.out.println("Relative: " + path);
    		} else {
    			//TODO throw exception
    			System.out.println("File could not be resolved");
    		}
    
    ...
    		
    	}

IMN logo majestic logo threadwatch logo seochat tools logo