This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I want to select files from the path specified and as per the file naming pattern provided, for eg. findFiles("c:\fun","*.*") should print all files in the directory c:\fun. Can anyone illustrate an example to accomplish this.
I know about FileNameFilter, which is an interface. Actually I want to apply a pattern like *.*, *java* on filenames in accept() method of FileNameFilter. I have included java.util.regexp package to accomplish this, but Iam getting an exception as follows.
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0 *str ^ at java.util.regex.Pattern.error(Pattern.java:1489) at java.util.regex.Pattern.sequence(Pattern.java:1606) at java.util.regex.Pattern.expr(Pattern.java:1506) at java.util.regex.Pattern.compile(Pattern.java:1274) at java.util.regex.Pattern.<init>(Pattern.java:1030) at java.util.regex.Pattern.compile(Pattern.java:777) at ListFiles$1.accept(ListFiles.java:19) at java.io.File.list(File.java:951) at ListFiles.printList(ListFiles.java:24) at ListFiles.toString(ListFiles.java:58) at java.lang.String.valueOf(String.java:2177) at java.io.PrintStream.print(PrintStream.java:462) at java.io.PrintStream.println(PrintStream.java:599) at ListFiles.main(ListFiles.java:75)
As Iam not familiar with regexp package, can anyone suggest how to filter files with pattern *.*, *java*.
Regex seems like the way to go. However, the syntax for regexes is different from what you are used to with file matching. For instance, the * in a regex means to match 0 or more of the PREVIOUS CHARACTER in the regex. So "a*" matches zero or more a's. You are getting an error because there is no preceding character. To match any character, you use . (dot). Note that . has special meaning, so to match a literal . you need to escape it with \. But \ has special meaning in a Javastring you need to escape it. To put this altogether in a coerent example, a regular expression that is equivalent to *.java will be ".*\\.java".