{"id":942,"date":"2018-09-17T18:40:44","date_gmt":"2018-09-17T09:40:44","guid":{"rendered":"https:\/\/chat-messenger.com\/?p=942"},"modified":"2018-12-23T01:53:04","modified_gmt":"2018-12-22T16:53:04","slug":"filesearch","status":"publish","type":"post","link":"https:\/\/chat-messenger.com\/en\/blog\/java\/filesearch","title":{"rendered":"Java recursively searches for files"},"content":{"rendered":"<h2 class=\"common_title\"><a name=\"0\"><strong>Java<\/strong> <strong>directory<\/strong>from (e.g. time, place, numerical quantity)<strong>recursive<\/strong>Search for files in<\/a><\/h2>\n<p>\n<strong>Java<\/strong> introduces a sample program that recursively searches for files in a specified directory, including subdirectories, and obtains a list of files that match the search criteria.<br \/>\nThey are equivalent to the UNIX command ls -R or the Windows command dir \/s.<br \/>\nYou can also specify * as a wildcard character in the file name to be searched, or use a regular expression to search.<\/p>\n<p>\u3000As an example of usage, the following recursively searches the directory filelist, including subdirectories, to obtain a list of files with the extension java.\n<\/p>\n<div class=\"point\">\nFileSearch search = new FileSearch();<br \/>\nFile[] files = search.listFiles(\"C:\/filelist\/\", \"*.java\");\n<\/div>\n<p><script type=\"text\/javascript\" src=\"https:\/\/chat-messenger.com\/js\/common.js?dd12sssas2223\" charset=\"UTF-8\"><\/script><br \/>\n<script type=\"text\/javascript\"> writePR(); <\/script><\/p>\n<h2 class=\"common_title\"><a name=\"1\">sample program<\/a><\/h2>\n<p><textarea readonly=\"readonly\" style=\"font-size: 13px; height: 400px;\" class=\"src\" onclick=\"this.focus();this.select()\">import java.io.File;<br \/>\nimport java.text.SimpleDateFormat;<br \/>\nimport java.util.Date;<br \/>\nimport java.util.TreeSet;<\/p>\n<p>\/**<br \/>\n *<br \/>\n *\/<br \/>\npublic class FileSearch {<\/p>\n<p>    public static final int TYPE_FILE_OR_DIR = 1;<br \/>\n    public static final int TYPE_FILE = 2;<br \/>\n    public static final int TYPE_DIR = 3;<\/p>\n<p>    \/**<br \/>\n     * From the specified directory [directoryPath],<br \/>\n     * Search the file [fileName] to be searched recursively and find the corresponding file.<br \/>\n     * Returns a list of file objects.<br \/>\n     *<br \/>\n     * example)<br \/>\n     * File[] files =listFiles(\u201cC:\/filelist\/\u201d, \u201c*.java\u201d);<br \/>\n     * The example above searches the directory filelist recursively and<br \/>\n     * Get a list of files with the extension java.<br \/>\n     *<br \/>\n     * @param directoryPath Path representing the directory to search<br \/>\n     * @param fileName File name to search for<br \/>\n     * You can specify * as a wildcard character in the file name.<br \/>\n     * @return File object matching the search<br \/>\n     *\/<br \/>\n    public File[] listFiles(String directoryPath, String fileName) {<br \/>\n        \/\/ Convert * as wildcard character to regular expression<br \/>\n        if (fileName != null) {<br \/>\n            fileName = fileName.replace(\u201c.\u201d, \u201c\\\\.\u201d);<br \/>\n            fileName = fileName.replace(\u201c*\u201d, \u201c.*\u201d);<br \/>\n        }<br \/>\n        return listFiles(directoryPath, fileName, TYPE_FILE, true, 0);<br \/>\n    }<\/p>\n<p>    \/**<br \/>\n     * From the specified directory [directoryPath], specified as a regular expression<br \/>\n     * Search recursively for the file to be searched [fileNamePattern],<br \/>\n     * Returns a list of applicable file objects.<br \/>\n     *<br \/>\n     * You can also use the search condition to determine whether the file&#039;s update date has passed the specified number of days.<br \/>\n     * Can be specified.<br \/>\n     *<br \/>\n     * example)<br \/>\n     * File[] files =<br \/>\n     * listFiles(\u201cC:\/filelist\/\u201d, \u201c*.java\u201d,TYPE_FILE, true, 2);<br \/>\n     * In the above example, the directory filelist is searched recursively and updated less than 7 days ago.<br \/>\n     * Get a list of files with extension java.<br \/>\n     *<br \/>\n     * @param directoryPath Path representing the directory to search<br \/>\n     * @param fileNamePattern File name to search for [regular expression]<br \/>\n     * @param type The corresponding file object is specified by [type].<br \/>\n     * The following can be specified<br \/>\n     * TYPE_FILE_OR_DIR\u30fb\u30fb\u30fbFile and directory<br \/>\n     * TYPE_FILE\u30fb\u30fb\u30fbFile<br \/>\n     * TYPE_DIR\u30fb\u30fb\u30fbDirectory<br \/>\n     * @param isRecursive true to search recursively<br \/>\n     * @param period Search for files whose update date has passed the specified number of days.<br \/>\n     * Can be set whether or not<br \/>\n     * Not applicable if 0<br \/>\n     * If 1 or more, search files after the specified number of days<br \/>\n     * If less than -1, search files older than the specified number of days<br \/>\n     * @return File object matching the search<br \/>\n     *\/<br \/>\n    public File[] listFiles(String directoryPath,<br \/>\n            String fileNamePattern, int type,<br \/>\n            boolean isRecursive, int period) {<\/p>\n<p>        File dir = new File(directoryPath);<br \/>\n        if (!dir.isDirectory()) {<br \/>\n            throw new IllegalArgumentException<br \/>\n            (\u201cPath specified in argument[\u201d + dir.getAbsolutePath() +<br \/>\n                    \u201c] is not a directory.\u201d);<br \/>\n        }<br \/>\n        File[] files = dir.listFiles();<br \/>\n        \/\/ its output<br \/>\n        for (int i = 0; i &lt; files.length; i++) {<br \/>\n            File file = files[i];<br \/>\n            addFile(type, fileNamePattern, set, file, period);<br \/>\n            \/\/ Search recursively and add to list recursively if it is a directory<br \/>\n            if (isRecursive &amp;&amp; file.isDirectory()) {<br \/>\n                listFiles(file.getAbsolutePath(), fileNamePattern,<br \/>\n                            type, isRecursive, period);<br \/>\n            }<br \/>\n        }<br \/>\n        return (File[]) set.toArray(new File[set.size()]);<br \/>\n    }<\/p>\n<p>    private void addFile(int type, String match, TreeSet set,<br \/>\n            File file,int period) {<br \/>\n        switch (type) {<br \/>\n        case TYPE_FILE:<br \/>\n            if (!file.isFile()) {<br \/>\n                return;<br \/>\n            }<br \/>\n            break;<br \/>\n        case TYPE_DIR:<br \/>\n            if (!file.isDirectory()) {<br \/>\n                return;<br \/>\n            }<br \/>\n            break;<br \/>\n        }<br \/>\n        if (match != null &amp;&amp; !file.getName().matches(match)) {<br \/>\n            return;<br \/>\n        }<br \/>\n        \/\/ If there is a specification whether the specified number of days have passed<br \/>\n        if (period != 0) {<br \/>\n            \/\/ File update date<br \/>\n            Date lastModifiedDate = new Date(file.lastModified());<br \/>\n            String lastModifiedDateStr = new SimpleDateFormat(\u201cyyyyMMdd\u201d)<br \/>\n                    .format(lastModifiedDate);<\/p>\n<p>            \/\/ Specified date (calculated in milliseconds per day)<br \/>\n            long oneDayTime = 24L * 60L * 60L * 1000L;<br \/>\n            long periodTime = oneDayTime * Math.abs(period);<br \/>\n            Date designatedDate =<br \/>\n                new Date(System.currentTimeMillis() \u2013 periodTime);<br \/>\n            String designatedDateStr = new SimpleDateFormat(\u201cyyyyMMdd\u201d)<br \/>\n                    .format(designatedDate);<br \/>\n            if (period &gt; 0) {<br \/>\n                if (lastModifiedDateStr.compareTo(designatedDateStr) &lt; 0) {<br \/>\n                    return;<br \/>\n                }<br \/>\n            } else {<br \/>\n                if (lastModifiedDateStr.compareTo(designatedDateStr) &gt; 0) {<br \/>\n                    return;<br \/>\n                }<br \/>\n            }<br \/>\n        }<br \/>\n        \/\/ Store in list if all conditions are met<br \/>\n        set.add(file);<\/p>\n<p>    }<\/p>\n<p>    \/** Use TreeSet to sort alphabetically. *\/<br \/>\n    private TreeSet set = new TreeSet();<\/p>\n<p>    \/**<br \/>\n     * If you want to continue using the instance after creating it, use this method.<br \/>\n     * Call must be cleared.<br \/>\n     * example)<br \/>\n     * FileSearch search = new FileSearch();<br \/>\n     * File[] f1 = search.listFiles(C:\/filelist\/\u201d, \u201c*.java\u201d);<br \/>\n     * search.clear();<br \/>\n     * File[] f2 = search.listFiles(\u201cC:\/filelist\/\u201d, \u201c*.jsp\u201d);<br \/>\n     *\/<br \/>\n    public void clear(){<br \/>\n    \tset.clear();<br \/>\n    }<br \/>\n}<br \/>\n<\/textarea><\/p>\n\n<h2 class=\"common_title\"><a name=\"2\">Execution Result<\/a><\/h2>\n<p>\n\u3000To check the sample program, we created a filelist directory and prepared the following files.<br \/>\n<br \/>\nThe file name and update date are displayed.<\/p>\n<p>The current date is<strong>2007\/08\/18<\/strong>Suppose it is.\n<\/p>\n<pre class=\"console\">C:\\filelist\r\n    \u2502 aaa.java 2007\/08\/18\r\n    \u2502 bbb.java 2007\/08\/18\r\n    \u2514\u2500dir\r\n           ccc.java 2007\/07\/17\r\n           ddd.java 2007\/08\/18\r\n           eee.jpg 2007\/08\/16\r\n<\/pre>\n<p>\u25c6Example of Execution<br \/>\n<textarea readonly=\"readonly\" style=\"font-size: 13px; height: 400px;\" class=\"src\" onclick=\"this.focus();this.select()\">  public static void main(String[] args) {<br \/>\n      String path = &#8220;C:\\\\filelist&#8221;;<br \/>\n      FileSearch search = new FileSearch();<\/p>\n<p>      System.out.println(\u201c\\n\u25cfGet all files\u201d);<br \/>\n      File[] files = search.listFiles(path, null);<br \/>\n      printFileList(files);<br \/>\n      search.clear();<\/p>\n<p>      System.out.println(\u201c\\n\u25cfGet file with extension java\u201d);<br \/>\n      files = search.listFiles(path, \u201c*.java\u201d);<br \/>\n      printFileList(files);<br \/>\n      search.clear();<\/p>\n<p>      System.out.println(\u201c\\n\u25cfGet all files and directories\u201d);<br \/>\n      files = search.listFiles(path, null,search.TYPE_FILE_OR_DIR, true, 0);<br \/>\n      printFileList(files);<br \/>\n      search.clear();<\/p>\n<p>      System.out.println(\u201c\\n\u25cfGet files updated within 2 days from the current date\u201d);<br \/>\n      files = search.listFiles(path, null,search.TYPE_FILE, true, 2);<br \/>\n      printFileList(files);<br \/>\n      search.clear();<\/p>\n<p>      System.out.println(\u201c\\n\u25cfGet old files older than 30 days from the current date\u201d);<br \/>\n      files = search.listFiles(path, null,search.TYPE_FILE, true, -30);<br \/>\n      printFileList(files);<br \/>\n      search.clear();<br \/>\n  }<\/p>\n<p>  private static void printFileList(File[] files) {<br \/>\n      for (int i = 0; i &lt; files.length; i++) {<br \/>\n          File file = files[i];<br \/>\n          System.out.println((i + 1) + \u201c: \u201d + file);<br \/>\n      }<br \/>\n  }<br \/>\n<\/textarea><br \/>\n<br \/>\n\u25c6Output result<\/p>\n<pre class=\"console\">Retrieve all files\r\n1: C:\\filelist\\aaa.java\r\n2: C:\\filelist\\bbb.java\r\n3:C:\\filelist\\dir\\ccc.java\r\n4: C:\\filelist\\dir\\ddd.java\r\n5: C:\\filelist\\dir\\dir\\eee.jpg\r\n\r\nObtaining a file with the extension java\r\n1: C:\\filelist\\aaa.java\r\n2: C:\\filelist\\bbb.java\r\n3: C:\\filelist\\dir\\ccc.java\r\n4: C:\\filelist\\dir\\ddd.java\r\n\r\nGet all files and directories\r\n1: C:\\filelist\\aaa.java\r\n2: C:\\filelist\\bbb.java\r\n3: C:\\filelist\\dir\r\n4: C:\\filelist\\dir\\ccc.java\r\n5: C:\\filelist\\dir\\ddd.java\r\n6: C:\\filelist\\dir\\dir\\eee.jpg\r\n\r\nObtaining files that have been updated since two days ago from the current date\r\n1: C:\\filelist\\aaa.java\r\n2: C:\\filelist\\bbb.java\r\n3: C:\\filelist\\dir\\ddd.java\r\n4: C:\\filelist\\dir\\dir\\eee.jpg\r\n\r\nRetrieve files older than 30 days from the current date\r\n1: C:\\filelist\\dir\\ccc.java\r\n<\/pre>","protected":false},"excerpt":{"rendered":"<p>Java Search for files recursively from a directory In Java, from a specified directory, including subdirectories [\u2026]<\/p>","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"swell_btn_cv_data":""},"categories":[19],"tags":[],"_links":{"self":[{"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/posts\/942"}],"collection":[{"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/comments?post=942"}],"version-history":[{"count":4,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/posts\/942\/revisions"}],"predecessor-version":[{"id":1881,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/posts\/942\/revisions\/1881"}],"wp:attachment":[{"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/media?parent=942"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/categories?post=942"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/tags?post=942"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}