001package algs35;
002import stdlib.*;
003import java.io.File;
004/* ***********************************************************************
005 *  Compilation:  javac FileIndex.java
006 *  Execution:    java FileIndex file1.txt file2.txt file3.txt ...
007 *  Dependencies: ST.java SET.java In.java StdIn.java StdOut.java
008 *  Data files:   http://algs4.cs.princeton.edu/35applications/ex1.txt
009 *                http://algs4.cs.princeton.edu/35applications/ex2.txt
010 *                http://algs4.cs.princeton.edu/35applications/ex3.txt
011 *                http://algs4.cs.princeton.edu/35applications/ex4.txt
012 *
013 *  % java FileIndex ex*.txt
014 *  age
015 *   ex3.txt
016 *   ex4.txt
017 * best
018 *   ex1.txt
019 * was
020 *   ex1.txt
021 *   ex2.txt
022 *   ex3.txt
023 *   ex4.txt
024 *
025 *  % java FileIndex *.txt
026 *
027 *  % java FileIndex *.java
028 *
029 *************************************************************************/
030
031public class FileIndex {
032
033        public static void main(String[] args) {
034                args = new String[] { "data/ex1.txt", "data/ex2.txt", "data/ex3.txt", "data/ex4.txt" };
035                StdIn.fromString ("age best was");
036
037                // key = word, value = set of files containing that word
038                ST<String, SET<File>> st = new ST<>();
039
040                // create inverted index of all files
041                StdOut.println("Indexing files");
042                for (String filename : args) {
043                        StdOut.println("  " + filename);
044                        File file = new File(filename);
045                        In in = new In(file);
046                        while (!in.isEmpty()) {
047                                String word = in.readString();
048                                if (!st.contains(word)) st.put(word, new SET<>());
049                                SET<File> set = st.get(word);
050                                set.add(file);
051                        }
052                }
053
054
055                // read queries from standard input, one per line
056                while (!StdIn.isEmpty()) {
057                        String query = StdIn.readString();
058                        StdOut.println(query);
059                        if (st.contains(query)) {
060                                SET<File> set = st.get(query);
061                                for (File file : set) {
062                                        StdOut.println("  " + file.getName());
063                                }
064                        }
065                }
066
067        }
068
069}