views:

707

answers:

2

Hi,

I have a class Test in C:/proj/test_xml/Test.java. Given parser.parse("test.xml"); I need a way to parse test.xml whether it is in current directory, proj or in C:/ Also, the solution should not make use of java.io

Thanks

A: 

I'm not sure I've understood your question but I assume you would like to search for a file in different locations, a finite number of arbitary directories. The last requirement sounds particularly awful... why not using java.io? The simplest solution that comes to (my) mind would in fact be:

String[] filenames = { "c://a.pdf", "c://airu//a.pdf" };
File f = null;
boolean found = false;
for (String filename : filenames)
{
  f = new File(filename);
  found = f.exists(); 
  if (found) break;
}
if (!found) 
{
  throw new RuntimeException("file nowhere to be found");
}
System.out.println("file " + f.getName() + " found");

Try and add some details to your question (edit) please.

Manrico Corazzi
A: 

Try a loop until parsing doesn't throw an IOException anymore:

String filename="test.xml";
int tries=3;
while( tries-->0 ) {
    try {
        parser.parse(filename);
        break;
    } catch( FileNotFoundException e ) {
        // FileNotFound expected
        filename="../"+filename;
    }
}

If tries == 0, it didn't find the file at all. For a DOM parser, need to retain the Document object returned from parser.parse().