Java: Determine if String is a URL/URI or file

In the spirit of making a more polymorphous app, you may need to pull off this trick, as I did in a recent assignment at Berkeley. I compiled a few different ways of getting the job done:
public boolean isLocalFile(String file) {
     try {
         new URL(file);
         return false;
     } catch (MalformedURLException e) {
         return true;
    }}
there’s also a util for this in Android’s toolkit (not worth grabbing unless you’re specifically writing for Android, though).
another semi-related thing;
  1. Make sure the filename is correct (proper capitalization, matching extension etc – as already suggested).
  2. Use the Class.getResource method to locate your file in the classpath – don’t rely on the current directory:
    URL url = insertionSort.class.getResource("10_Random");
    
    File file = new File(url.toURI());
  3. Specify the absolute file path via command-line arguments:
    File file = new File(args[0]);

In Eclipse:

  1. Choose “Run configurations”
  2. Go to the “Arguments” tab
  3. Put your “c:/Users/HackR/somewhere/10_myjava.txt.or.something” into the “Program arguments” section

Java