How to get real path of an image in Java?

A Java program on CodeEval had to accept a file path as an argument. I used a command line argument to do this, but I get an exception as below when I submitted my code on CodeEval. What are some potential solutions to this problem?

  • Exception in thread "main" java.util.NoSuchElementException     at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)     at java.util.StringTokenizer.nextElement(StringTokenizer.java:407)     at Main.FileRead(Main.java:61)     at Main.main(Main.java:26)

  • Answer:

    It looks like what you're doing is calling StringTokenizer.nextElement() (which calls StringTokenizer.nextToken()) when there are no more tokens in the string you're parsing.  Under those circumstances, it will throw a NoSuchElementException. The way you usually use StringTokenizer is inside a loop which guards against this condition by using the StringTokenizer.hasMoreElements() (or StringTokenizer.hasMoreTokens()) method.  Thus: StringTokenizer tok = new StringTokenizer(someString); // splits on whitespace by default while (tok.hasMoreElements()) { String s = (String)(tok.nextElement()); // do something with "s" } To do this across an entire command line, you put it inside a second loop: public class CmdLineTokenizer { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { StringTokenizer tok = new StringTokenizer(args[i]); while (tok.hasMoreElements()) { String s = (String)(tok.nextElement()); // do something with "s" here } } } } Try a strategy like that, and your exception should go away. Hat tip: for the A2A.

Eric Bowersox at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.