[英]Java check if string is valid file
我想檢查字符串是否是有效的文件模式,我想要的是:
如果string = "/abc/def/apple.xml"
則return TRUE
如果string = "/abc/def/"
則return FALSE
如果string = "/abc/def"
則return FALSE
我的代碼:
String filepath = "/abc/def/apple.xml";
File f = new File(filepath);
if(f.isFile() && !f.isDirectory())
return true;
else
return false;
用我的代碼,我將字符串設置為/abc/def/apple.xml
或/abc/def/
,兩者都還返回false
,不確定為什么
如果您能夠使用Java 7(或更高版本),則可以使用新的新IO。 Oracle提供了有關此的教程:
http://docs.oracle.com/javase/tutorial/essential/io/check.html
您應該嘗試這樣:
String filePath = "yourPath/file.txt";
Path path = Paths.get(filePath);
System.out.println(Files.exists(path, LinkOption.NOFOLLOW_LINKS));
如果您非常確定文件路徑包含.xml,那么您也可以通過這種方式執行任務
String path="abc/bcd/efg.xml";
boolean temp=path.endsWith(".xml") ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.