Example usage for java.io File toString

List of usage examples for java.io File toString

Introduction

In this page you can find the example usage for java.io File toString.

Prototype

public String toString() 

Source Link

Document

Returns the pathname string of this abstract pathname.

Usage

From source file:Main.java

public static void main(String[] args) {
    File f = new File("test.txt");

    String str = f.toString();

    System.out.println("pathname string: " + str);

}

From source file:com.discursive.jccook.slide.GetExample.java

public static void main(String[] args) throws HttpException, IOException {
    HttpClient client = new HttpClient();

    String url = "http://www.discursive.com/jccook/dav/test.html";
    Credentials credentials = new UsernamePasswordCredentials("davuser", "davpass");

    // List resources in top directory
    WebdavResource resource = new WebdavResource(url, credentials);

    System.out.println("The three ways to Read resources.");

    // Read to a temporary file
    File tempFile = new File(resource.getName());
    resource.getMethod(tempFile);/*  www.j a va2s .  c  om*/
    System.out.println("1. " + resource.getName() + " saved in file: " + tempFile.toString());

    // Read as a String
    String resourceData = resource.getMethodDataAsString();
    System.out.println("2. Contents of " + resource.getName() + " as String.");
    System.out.println(resourceData);

    // Read with a stream
    InputStream resourceStream = resource.getMethodData();
    Reader reader = new InputStreamReader(resourceStream);
    StringWriter writer = new StringWriter();
    while (reader.ready()) {
        writer.write(reader.read());
    }
    System.out.println("3. Contents of " + resource.getName() + " from InputStream.");
    System.out.println(writer.toString());

    resource.close();

}

From source file:dk.statsbiblioteket.util.qa.PackageScannerDriver.java

/**
 * @param args The command line arguments.
 * @throws IOException If command line arguments can't be passed or there
 *                     is an error reading class files.
 *///from  w ww.j  a  v a  2 s.  c  om
@SuppressWarnings("deprecation")
public static void main(final String[] args) throws IOException {
    Report report;
    CommandLine cli = null;
    String reportType, projectName, baseSrcDir, targetPackage;
    String[] targets = null;

    // Build command line options
    CommandLineParser cliParser = new PosixParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print help message and exit");
    options.addOption("n", "name", true, "Project name, default 'Unknown'");
    options.addOption("o", "output", true, "Type of output, 'plain' or 'html', default is html");
    options.addOption("p", "package", true, "Only scan a particular package in input dirs, use dotted "
            + "package notation to refine selections");
    options.addOption("s", "source-dir", true,
            "Base source dir to use in report, can be a URL. " + "@FILE@ and @MODULE@ will be escaped");

    // Parse and validate command line
    try {
        cli = cliParser.parse(options, args);
        targets = cli.getArgs();
        if (args.length == 0 || targets.length == 0 || cli.hasOption("help")) {
            throw new ParseException("Not enough arguments, no input files");
        }
    } catch (ParseException e) {
        printHelp(options);
        System.exit(1);
    }

    // Extract information from command line
    reportType = cli.getOptionValue("output") != null ? cli.getOptionValue("output") : "html";

    projectName = cli.getOptionValue("name") != null ? cli.getOptionValue("name") : "Unknown";

    baseSrcDir = cli.getOptionValue("source-dir") != null ? cli.getOptionValue("source-dir")
            : System.getProperty("user.dir");

    targetPackage = cli.getOptionValue("package") != null ? cli.getOptionValue("package") : "";
    targetPackage = targetPackage.replace(".", File.separator);

    // Set up report type
    if ("plain".equals(reportType)) {
        report = new BasicReport();
    } else {
        report = new HTMLReport(projectName, System.out, baseSrcDir);
    }

    // Do actual scanning of provided targets
    for (String target : targets) {
        PackageScanner scanner;
        File f = new File(target);

        if (f.isDirectory()) {
            scanner = new PackageScanner(report, f, targetPackage);
        } else {
            String filename = f.toString();
            scanner = new PackageScanner(report, f.getParentFile(),
                    filename.substring(filename.lastIndexOf(File.separator) + 1));
        }
        scanner.scan();
    }

    // Cloce the report before we exit
    report.end();
}

From source file:net.skyebook.zerocollada.ZeroCollada.java

/**
 * @param args// w w w.j  av a  2 s .  com
 * @throws ParseException 
 * @throws IOException 
 * @throws JDOMException 
 */
public static void main(String[] args) throws ParseException, JDOMException, IOException {
    // Setup Apache Commons CLI
    optionsSetup();

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (args.length == 0 || cmd.hasOption(ZCOpts.help)) {
        showHelp();
    }

    // was there a valid operation specified?
    if (hasValidOption(cmd)) {
        File fileFromCommandLine = new File(args[args.length - 1]);
        if (!fileFromCommandLine.exists()) {
            System.err.println(
                    "The file located at " + fileFromCommandLine.toString() + " does not exist!  Qutting.");
            return;
        } else if (fileFromCommandLine.isFile() && fileFromCommandLine.toString().endsWith(".dae")) {
            // we've been given a single file.  Act on this single file
            doRequestedAction(fileFromCommandLine, cmd);
        } else if (fileFromCommandLine.isDirectory()) {
            // We've been given a directory of files process the ones that are .dae
            for (File file : fileFromCommandLine.listFiles()) {
                if (file.isFile() && file.toString().endsWith(".dae")) {
                    doRequestedAction(file, cmd);
                } else {
                    System.err.println(file.toString() + " does not seem to be a COLLADA file");
                }
            }
        }
    } else {
        // Then why are we here?
        if (cmd.hasOption(ZCOpts.includeY)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        } else if (cmd.hasOption(ZCOpts.anchorCenter)) {
            System.err.println(
                    "You have used the " + ZCOpts.includeY + " option but have not asked for a transform (t)");
        }
    }

}

From source file:it.unimi.di.big.mg4j.tool.URLMPHVirtualDocumentResolver.java

public static void main(final String[] arg) throws JSAPException, IOException {
    final SimpleJSAP jsap = new SimpleJSAP(URLMPHVirtualDocumentResolver.class.getName(),
            "Builds a URL document resolver from a sequence of URIs, extracted typically using ScanMetadata, using a suitable function. You can specify that the list is sorted, in which case it is possible to generate a resolver that occupies less space.",
            new Parameter[] {
                    new Switch("sorted", 's', "sorted",
                            "URIs are sorted: use a monotone minimal perfect hash function."),
                    new Switch("iso", 'i', "iso",
                            "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)."),
                    new FlaggedOption("bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b',
                            "buffer-size", "The size of the I/O buffer used to read terms."),
                    new FlaggedOption("class", MG4JClassParser.getParser(), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'c', "class",
                            "A class used to create the function from URIs to their ranks; defaults to it.unimi.dsi.sux4j.mph.MHWCFunction for non-sorted inputs, and to it.unimi.dsi.sux4j.mph.TwoStepsLcpMonotoneMinimalPerfectHashFunction for sorted inputs."),
                    new FlaggedOption("width", JSAP.INTEGER_PARSER, Integer.toString(Long.SIZE),
                            JSAP.NOT_REQUIRED, 'w', "width",
                            "The width, in bits, of the signatures used to sign the function from URIs to their rank."),
                    new FlaggedOption("termFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o',
                            "offline",
                            "Read terms from this file (without loading them into core memory) instead of standard input."),
                    new FlaggedOption("uniqueUris", JSAP.INTSIZE_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'U', "unique-uris",
                            "Force URIs to be unique by adding random garbage at the end of duplicates; the argument is an upper bound for the number of URIs that will be read, and will be used to create a Bloom filter."),
                    new UnflaggedOption("resolver", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.NOT_GREEDY, "The filename for the resolver.") });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        return;/*from w w  w.  j a v  a2s .c  om*/

    final int bufferSize = jsapResult.getInt("bufferSize");
    final String resolverName = jsapResult.getString("resolver");
    //final Class<?> tableClass = jsapResult.getClass( "class" );
    final boolean iso = jsapResult.getBoolean("iso");
    String termFile = jsapResult.getString("termFile");

    BloomFilter<Void> filter = null;
    final boolean uniqueURIs = jsapResult.userSpecified("uniqueUris");
    if (uniqueURIs)
        filter = BloomFilter.create(jsapResult.getInt("uniqueUris"));

    final Collection<? extends CharSequence> collection;
    if (termFile == null) {
        ArrayList<MutableString> termList = new ArrayList<MutableString>();
        final ProgressLogger pl = new ProgressLogger();
        pl.itemsName = "URIs";
        final LineIterator termIterator = new LineIterator(
                new FastBufferedReader(new InputStreamReader(System.in, "UTF-8"), bufferSize), pl);

        pl.start("Reading URIs...");
        MutableString uri;
        while (termIterator.hasNext()) {
            uri = termIterator.next();
            if (uniqueURIs)
                makeUnique(filter, uri);
            termList.add(uri.copy());
        }
        pl.done();

        collection = termList;
    } else {
        if (uniqueURIs) {
            // Create temporary file with unique URIs
            final ProgressLogger pl = new ProgressLogger();
            pl.itemsName = "URIs";
            pl.start("Copying URIs...");
            final LineIterator termIterator = new LineIterator(
                    new FastBufferedReader(new InputStreamReader(new FileInputStream(termFile)), bufferSize),
                    pl);
            File temp = File.createTempFile(URLMPHVirtualDocumentResolver.class.getName(), ".uniqueuris");
            temp.deleteOnExit();
            termFile = temp.toString();
            final FastBufferedOutputStream outputStream = new FastBufferedOutputStream(
                    new FileOutputStream(termFile), bufferSize);
            MutableString uri;
            while (termIterator.hasNext()) {
                uri = termIterator.next();
                makeUnique(filter, uri);
                uri.writeUTF8(outputStream);
                outputStream.write('\n');
            }
            pl.done();
            outputStream.close();
        }
        collection = new FileLinesCollection(termFile, "UTF-8");
    }
    LOGGER.debug("Building function...");
    final int width = jsapResult.getInt("width");
    if (jsapResult.getBoolean("sorted"))
        BinIO.storeObject(
                new URLMPHVirtualDocumentResolver(
                        new ShiftAddXorSignedStringMap(collection.iterator(),
                                new TwoStepsLcpMonotoneMinimalPerfectHashFunction<CharSequence>(collection,
                                        iso ? TransformationStrategies.prefixFreeIso()
                                                : TransformationStrategies.prefixFreeUtf16()),
                                width)),
                resolverName);
    else
        BinIO.storeObject(
                new URLMPHVirtualDocumentResolver(new ShiftAddXorSignedStringMap(collection.iterator(),
                        new MWHCFunction<CharSequence>(collection,
                                iso ? TransformationStrategies.iso() : TransformationStrategies.utf16()),
                        width)),
                resolverName);
    LOGGER.debug(" done.");
}

From source file:com.ms.commons.test.tool.GenerateTestCase.java

public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Usage:\r\n.frameworktest_maketests antx|maven fileter");
        System.exit(-1);//from  ww w  .ja  va  2s .c o m
    }

    final com.ms.commons.test.runner.filter.expression.internal.Expression filterExpression;
    try {
        System.out.println("Filter: " + args[1]);
        filterExpression = ExpressionParseUtil.parse(args[1], new SimpleExpressionBuiler() {

            public AbstractSimpleExpression build(String value) {
                return new StringExpressionImpl(value);
            }
        });
    } catch (ParseException e) {
        throw ExceptionUtil.wrapToRuntimeException(e);
    }
    final FullClassNameFilter fullClassNameFilter = new FullClassNameFilter() {

        public boolean accept(String fullClassName) {

            return ((Boolean) filterExpression.evaluate(fullClassName)).booleanValue();
        }
    };

    String userDir = System.getProperty("user.dir");

    ProjectPath pp = getProjectPath(args[0]);

    final String mainSource = userDir + File.separator + pp.getMainSource();
    final String testSource = userDir + File.separator + pp.getTestSource();

    FileUtil.listFiles(null, new File(mainSource), new FileFilter() {

        public boolean accept(File pathname) {
            if (pathname.isDirectory()) {
                return !pathname.toString().contains(".svn");
            }
            if (pathname.toString().contains(".svn")) {
                return false;
            }
            if (!pathname.toString().toLowerCase().endsWith(".java")) {
                return false;
            }
            try {
                processJavaFile(pathname, testSource, fullClassNameFilter);
            } catch (Exception e) {
                System.err.println("Parse java file failed:" + pathname);
                e.printStackTrace();
            }
            return false;
        }
    });
}

From source file:esiptestbed.mudrod.ontology.process.LocalOntology.java

public static void main(String[] args) throws Exception {

    // boolean options
    Option helpOpt = new Option("h", "help", false, "show this help message");
    // argument options
    Option ontDirOpt = Option.builder(ONT_DIR).required(true).numberOfArgs(1).hasArg(true)
            .desc("A directory containing .owl files.").argName(ONT_DIR).build();

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);/*from  ww w  .ja  va2 s. com*/
    options.addOption(ontDirOpt);

    String ontDir;
    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(ONT_DIR)) {
            ontDir = line.getOptionValue(ONT_DIR).replace("\\", "/");
        } else {
            ontDir = LocalOntology.class.getClassLoader().getResource("ontology").getFile();
        }
        if (!ontDir.endsWith("/")) {
            ontDir += "/";
        }
    } catch (Exception e) {
        LOG.error("Error whilst processing main method of LocalOntology.", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LocalOntology: 'ontDir' argument is mandatory. ", options, true);
        return;
    }
    File fileDir = new File(ontDir);
    //Fail if the input is not a directory.
    if (fileDir.isDirectory()) {
        List<String> owlFiles = new ArrayList<>();
        for (File owlFile : fileDir.listFiles()) {
            owlFiles.add(owlFile.toString());
        }
        MudrodEngine mEngine = new MudrodEngine();
        Properties props = mEngine.loadConfig();
        Ontology ontology = new OntologyFactory(props).getOntology();
        //convert to correct iput for ontology loading.
        String[] owlArray = new String[owlFiles.size()];
        owlArray = owlFiles.toArray(owlArray);
        ontology.load(owlArray);

        String[] terms = new String[] { "Glacier ice" };
        //Demonstrate that we can do basic ontology heirarchy navigation and log output.
        for (Iterator<OntClass> i = getParser().rootClasses(getModel()); i.hasNext();) {

            //print Ontology Class Hierarchy
            OntClass c = i.next();
            renderHierarchy(System.out, c, new LinkedList<>(), 0);

            for (Iterator<OntClass> subClass = c.listSubClasses(true); subClass.hasNext();) {
                OntClass sub = subClass.next();
                //This means that the search term is present as an OntClass
                if (terms[0].equalsIgnoreCase(sub.getLabel(null))) {
                    //Add the search term(s) above to the term cache.
                    for (int j = 0; j < terms.length; j++) {
                        addSearchTerm(terms[j], sub);
                    }

                    //Query the ontology and return subclasses of the search term(s)
                    for (int k = 0; k < terms.length; k++) {
                        Iterator<String> iter = ontology.subclasses(terms[k]);
                        while (iter.hasNext()) {
                            LOG.info("Subclasses >> " + iter.next());
                        }
                    }

                    //print any synonymic relationships to demonstrate that we can 
                    //undertake synonym-based query expansion
                    for (int l = 0; l < terms.length; l++) {
                        Iterator<String> iter = ontology.synonyms(terms[l]);
                        while (iter.hasNext()) {
                            LOG.info("Synonym >> " + iter.next());
                        }
                    }
                }
            }
        }

        mEngine.end();
    }

}

From source file:gov.nasa.jpl.mudrod.ontology.process.LocalOntology.java

public static void main(String[] args) throws Exception {

    // boolean options
    Option helpOpt = new Option("h", "help", false, "show this help message");
    // argument options
    Option ontDirOpt = OptionBuilder.hasArg(true).withArgName(ONT_DIR)
            .withDescription("A directory containing .owl files.").isRequired(false).create();

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);/*from   w  ww . j  a  va  2s  . co  m*/
    options.addOption(ontDirOpt);

    String ontDir;
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(ONT_DIR)) {
            ontDir = line.getOptionValue(ONT_DIR).replace("\\", "/");
        } else {
            ontDir = LocalOntology.class.getClassLoader().getResource("ontology").getFile();
        }
        if (!ontDir.endsWith("/")) {
            ontDir += "/";
        }
    } catch (Exception e) {
        LOG.error("Error whilst processing main method of LocalOntology.", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LocalOntology: 'ontDir' argument is mandatory. ", options, true);
        return;
    }
    File fileDir = new File(ontDir);
    //Fail if the input is not a directory.
    if (fileDir.isDirectory()) {
        List<String> owlFiles = new ArrayList<>();
        for (File owlFile : fileDir.listFiles()) {
            owlFiles.add(owlFile.toString());
        }
        MudrodEngine mEngine = new MudrodEngine();
        Properties props = mEngine.loadConfig();
        Ontology ontology = new OntologyFactory(props).getOntology();
        //convert to correct iput for ontology loading.
        String[] owlArray = new String[owlFiles.size()];
        owlArray = owlFiles.toArray(owlArray);
        ontology.load(owlArray);

        String[] terms = new String[] { "Glacier ice" };
        //Demonstrate that we can do basic ontology heirarchy navigation and log output.
        for (Iterator<OntClass> i = getParser().rootClasses(getModel()); i.hasNext();) {

            //print Ontology Class Hierarchy
            OntClass c = i.next();
            renderHierarchy(System.out, c, new LinkedList<>(), 0);

            for (Iterator<OntClass> subClass = c.listSubClasses(true); subClass.hasNext();) {
                OntClass sub = subClass.next();
                //This means that the search term is present as an OntClass
                if (terms[0].equalsIgnoreCase(sub.getLabel(null))) {
                    //Add the search term(s) above to the term cache.
                    for (int j = 0; j < terms.length; j++) {
                        addSearchTerm(terms[j], sub);
                    }

                    //Query the ontology and return subclasses of the search term(s)
                    for (int k = 0; k < terms.length; k++) {
                        Iterator<String> iter = ontology.subclasses(terms[k]);
                        while (iter.hasNext()) {
                            LOG.info("Subclasses >> " + iter.next());
                        }
                    }

                    //print any synonymic relationships to demonstrate that we can 
                    //undertake synonym-based query expansion
                    for (int l = 0; l < terms.length; l++) {
                        Iterator<String> iter = ontology.synonyms(terms[l]);
                        while (iter.hasNext()) {
                            LOG.info("Synonym >> " + iter.next());
                        }
                    }
                }
            }
        }

        mEngine.end();
    }

}

From source file:de.citec.sc.matoll.process.Matoll_CreateMax.java

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException,
        InstantiationException, IllegalAccessException, ClassNotFoundException, Exception {

    String directory;/*from   w  w  w. j  a va 2 s  .c  om*/
    String gold_standard_lexicon;
    String output_lexicon;
    String configFile;
    Language language;
    String output;

    Stopwords stopwords = new Stopwords();

    HashMap<String, Double> maxima;
    maxima = new HashMap<String, Double>();

    if (args.length < 3) {
        System.out.print("Usage: Matoll --mode=train/test <DIRECTORY> <CONFIG>\n");
        return;

    }

    //      Classifier classifier;

    directory = args[1];
    configFile = args[2];

    final Config config = new Config();

    config.loadFromFile(configFile);

    gold_standard_lexicon = config.getGoldStandardLexicon();

    String model_file = config.getModel();

    output_lexicon = config.getOutputLexicon();
    output = config.getOutput();

    language = config.getLanguage();

    LexiconLoader loader = new LexiconLoader();
    Lexicon gold = loader.loadFromFile(gold_standard_lexicon);

    Set<String> uris = new HashSet<>();
    //        Map<Integer,String> sentence_list = new HashMap<>();
    Map<Integer, Set<Integer>> mapping_words_sentences = new HashMap<>();

    //consider only properties
    for (LexicalEntry entry : gold.getEntries()) {
        try {
            for (Sense sense : entry.getSenseBehaviours().keySet()) {
                String tmp_uri = sense.getReference().getURI().replace("http://dbpedia.org/ontology/", "");
                if (!Character.isUpperCase(tmp_uri.charAt(0))) {
                    uris.add(sense.getReference().getURI());
                }
            }
        } catch (Exception e) {
        }
        ;
    }

    ModelPreprocessor preprocessor = new ModelPreprocessor(language);
    preprocessor.setCoreferenceResolution(false);
    Set<String> dep = new HashSet<>();
    dep.add("prep");
    dep.add("appos");
    dep.add("nn");
    dep.add("dobj");
    dep.add("pobj");
    dep.add("num");
    preprocessor.setDEP(dep);

    List<File> list_files = new ArrayList<>();

    if (config.getFiles().isEmpty()) {
        File folder = new File(directory);
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.toString().contains(".ttl"))
                list_files.add(file);
        }
    } else {
        list_files.addAll(config.getFiles());
    }
    System.out.println(list_files.size());

    int sentence_counter = 0;
    Map<String, Set<Integer>> bag_words_uri = new HashMap<>();
    Map<String, Integer> mapping_word_id = new HashMap<>();
    for (File file : list_files) {
        Model model = RDFDataMgr.loadModel(file.toString());
        for (Model sentence : getSentences(model)) {
            String reference = getReference(sentence);
            reference = reference.replace("http://dbpedia/", "http://dbpedia.org/");
            if (uris.contains(reference)) {
                sentence_counter += 1;
                Set<Integer> words_ids = getBagOfWords(sentence, stopwords, mapping_word_id);
                //TODO: add sentence preprocessing
                String obj = getObject(sentence);
                String subj = getSubject(sentence);
                preprocessor.preprocess(sentence, subj, obj, language);
                //TODO: also return marker if object or subject of property (in SPARQL this has to be optional of course)
                String parsed_sentence = getParsedSentence(sentence);
                try (FileWriter fw = new FileWriter("mapping_sentences_to_ids_goldstandard.tsv", true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        PrintWriter out = new PrintWriter(bw)) {
                    out.println(sentence_counter + "\t" + parsed_sentence);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for (Integer word_id : words_ids) {
                    if (mapping_words_sentences.containsKey(word_id)) {
                        Set<Integer> tmp_set = mapping_words_sentences.get(word_id);
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);

                    } else {
                        Set<Integer> tmp_set = new HashSet<>();
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);
                    }

                }
                if (bag_words_uri.containsKey(reference)) {
                    Set<Integer> tmp = bag_words_uri.get(reference);
                    for (Integer w : words_ids) {
                        tmp.add(w);

                    }
                    bag_words_uri.put(reference, tmp);
                } else {
                    Set<Integer> tmp = new HashSet<>();
                    for (Integer w : words_ids) {
                        tmp.add(w);
                    }
                    bag_words_uri.put(reference, tmp);
                }
            }

        }
        model.close();

    }

    PrintWriter writer = new PrintWriter("bag_of_words_only_goldstandard.tsv");
    StringBuilder string_builder = new StringBuilder();
    for (String r : bag_words_uri.keySet()) {
        string_builder.append(r);
        for (Integer i : bag_words_uri.get(r)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

    writer = new PrintWriter("mapping_words_to_sentenceids_goldstandard.tsv");
    string_builder = new StringBuilder();
    for (Integer w : mapping_words_sentences.keySet()) {
        string_builder.append(w);
        for (int i : mapping_words_sentences.get(w)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

}

From source file:io.fabric8.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);//w w  w  . jav a  2 s  . c om

    File baseDir = new File("/Users/kameshs/git/fabric8io/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

    } catch (Exception e) {
        e.printStackTrace();
    }

}