0

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

hades
  • 4,294
  • 9
  • 46
  • 71
  • i tried if(f.exists() && !f.isDirectory()) too, not work either – hades Dec 04 '14 at 10:15
  • Where is the file located? – Maroun Dec 04 '14 at 10:16
  • 1
    Do you want to check if the mentioned file exists at the given location or do you want to checking the string and see if that looks like a file name? – rajesh Dec 04 '14 at 10:17
  • actually this filepath is a string stored in database, i just want to validate the string before proceed. – hades Dec 04 '14 at 10:17
  • @rajesh i want to check the string and see if that looks like a file name – hades Dec 04 '14 at 10:18
  • I think your code checks for actual file existence and what you mean by this line "if file exist in a string" is checking the String str that it contains any file extension. – Jayesh Dec 04 '14 at 10:19
  • 1
    @user3172596 Do you not care if the file exists just that is looks like a file path? – James Fox Dec 04 '14 at 10:19
  • so you only want to check a string and decide if it's a file or folder based on it's name? example if it ends with .xml then it's a file? that won't work since you can name directories .xml as well... do you not care about the existance of the file at all? – MihaiC Dec 04 '14 at 10:29

3 Answers3

2

You should try this:

String filePath = "yourPath/file.txt"; 
Path path = Paths.get(filePath);
System.out.println(Files.exists(path, LinkOption.NOFOLLOW_LINKS));
Prateek
  • 6,785
  • 2
  • 24
  • 37
1

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

Roy van Rijn
  • 840
  • 7
  • 17
1

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") ;
Prateek
  • 6,785
  • 2
  • 24
  • 37
Kandy
  • 673
  • 9
  • 21