hades
hades

Reputation: 4704

Java check if string is valid file

I want to check if a string is a valid file pattern, what i want is:

if string = "/abc/def/apple.xml" then return TRUE

if string = "/abc/def/" then return FALSE

if string = "/abc/def" then return FALSE

My code:

String filepath = "/abc/def/apple.xml";
File f = new File(filepath);

if(f.isFile() && !f.isDirectory())
 return true;
else
  return false;

With my code i set string as /abc/def/apple.xml or /abc/def/, both also return false, not really sure why

Upvotes: 1

Views: 7918

Answers (3)

Kandy
Kandy

Reputation: 673

If you are pretty sure about filepath that it contain .xml than you can do your task in that manner also

String path="abc/bcd/efg.xml";
boolean temp=path.endsWith(".xml") ;

Upvotes: 1

Prateek
Prateek

Reputation: 6975

You should try this:

String filePath = "yourPath/file.txt"; 
Path path = Paths.get(filePath);
System.out.println(Files.exists(path, LinkOption.NOFOLLOW_LINKS));

Upvotes: 3

Roy van Rijn
Roy van Rijn

Reputation: 850

If you are able to use Java 7 (or better) you can use the new new IO. There is a tutorial from Oracle about this:

http://docs.oracle.com/javase/tutorial/essential/io/check.html

Upvotes: 1

Related Questions