簡體   English   中英

Java檢查字符串是否為有效文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM