简体   繁体   中英

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

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

You should try this:

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

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") ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM