Example usage for java.io File isDirectory

List of usage examples for java.io File isDirectory

Introduction

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

Prototype

public boolean isDirectory() 

Source Link

Document

Tests whether the file denoted by this abstract pathname is a directory.

Usage

From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    HelpFormatter formatter = new HelpFormatter();
    options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert")
            .longOpt("source").hasArg(true).build());
    options.addOption(Option.builder("t").argName("target").desc("the target file to store in")
            .longOpt("target").hasArg(true).build());
    options.addOption(Option.builder("h").desc("print help").build());

    try {// ww w . j  av a 2  s  . c  om
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            formatter.printHelp("converter", options);
        }
        File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir")));
        String name = source.getName();
        if (source.isDirectory()) {
            PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter();
            String[] ext = { "properties" };
            Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true);
            while (fileIterator.hasNext()) {
                File next = fileIterator.next();
                System.out.println(next);
                String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath());
                System.out.println(s);
                String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0];
                System.out.println("key = " + f);
                Properties p = new Properties();
                try {
                    p.load(new FileReader(next));
                    yamlConverter.addProperties(f, p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            yamlConverter.writeYaml(fileWriter);
            fileWriter.close();
        } else {
            Properties p = new Properties();
            p.load(new FileReader(source));
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter);
            fileWriter.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        formatter.printHelp("converter", options);
    }
}

From source file:edu.gslis.ts.ThriftToTREC.java

public static void main(String[] args) {
    try {//from ww  w  . j  av a2s . com
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String in = cmd.getOptionValue("i");
        String outfile = cmd.getOptionValue("o");
        String sentenceParser = cmd.getOptionValue("p");

        // Setup the filter
        ThriftToTREC f = new ThriftToTREC();

        if (in != null && outfile != null) {
            File infile = new File(in);
            if (infile.isDirectory()) {
                for (File file : infile.listFiles()) {
                    if (file.isDirectory()) {
                        for (File filefile : file.listFiles()) {
                            f.filter(filefile, new File(outfile), sentenceParser);
                        }
                    } else {
                        f.filter(file, new File(outfile), sentenceParser);
                    }
                }
            } else
                f.filter(infile, new File(outfile), sentenceParser);
        }

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

From source file:Main.java

public static void main(String[] args) {
    File file = new File("C://FileIO");
    boolean isFile = file.isFile();
    if (isFile) {
        System.out.println("a file.");
    } else {/* w  w  w.ja v  a2  s . c o  m*/
        System.out.println("not a file.");
    }
    boolean isDirectory = file.isDirectory();

    if (isDirectory) {
        System.out.println("a directory.");
    } else {
        System.out.println("not a directory.");
    }
}

From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java

public static void main(String[] args) throws InterruptedException {
    // create Options object
    Options options = new Options();
    // add conf file option
    options.addOption("c", true, "config file");
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;/*from  w  w w  .j  a  v  a 2 s.  com*/
    try {
        cmd = parser.parse(options, args);
        String configFile = cmd.getOptionValue("c");
        if (configFile == null) {
            Log.e(TAG, "The config file option was not provided");
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("d", options);
            System.exit(-1);
        } else {
            try {
                HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile);
                Path libdir = Paths.get(hubConfig.getLibdir());
                if (hubConfig.isDebugMode()) {
                    File dir = libdir.toFile();
                    if (dir.exists() && dir.isDirectory())
                        for (File file : dir.listFiles())
                            file.delete();
                }
                final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost());
                init(hubConfig);
                try {
                    server.start();
                } catch (IOException ioe) {
                    Log.e(TAG, "Couldn't start server:\n" + ioe);
                    System.exit(-1);
                }
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        server.stop();
                        Log.i(TAG, "Server stopped");
                    }
                });

                while (true) {
                    Thread.sleep(1000);
                }
            } catch (ConfigurationParsingException | IOException e) {
                System.out.println("1:" + e.getMessage());
                Log.e(TAG, e.getMessage());
                System.exit(-1);
            }
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        Log.e(TAG, e.getMessage());
        System.exit(-1);
    }
}

From source file:eu.digitisation.idiomaident.utils.ExtractTestSamples.java

public static void main(String args[]) {
    if (args.length < 3) {
        System.err.println("Usage: ExtractTextSamples " + "numSamples inFolder outCsvText");
    } else {/*from ww w. j av  a2  s  .  c o m*/
        int numSamples = Integer.parseInt(args[0]);
        File inFolder = new File(args[1]);
        File outFile = new File(args[2]);

        if (inFolder.exists() && inFolder.isDirectory()) {
            extractSamples(numSamples, inFolder, outFile);
        }
    }
}

From source file:com.px100systems.data.utility.RestoreUtility.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err.println("Usage: java -cp ... com.px100systems.data.utility.RestoreUtility "
                + "<springXmlConfigFile> <persisterBeanName> <backupDirectory> [compare]");
        return;/* w  w w. j  a  v  a2 s .co  m*/
    }

    FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + args[0]);
    try {
        PersistenceProvider persister = ctx.getBean(args[1], PersistenceProvider.class);

        File directory = new File(args[2]);
        if (!directory.isDirectory()) {
            System.err.println(directory.getName() + " is not a directory");
            return;
        }

        List<File> files = new ArrayList<File>();
        //noinspection ConstantConditions
        for (File file : directory.listFiles())
            if (BackupFile.isBackup(file))
                files.add(file);

        if (files.isEmpty()) {
            System.err.println(directory.getName() + " directory has no backup files");
            return;
        }

        if (args.length == 4 && args[3].equalsIgnoreCase("compare")) {
            final Map<String, Map<Long, RawRecord>> units = new HashMap<String, Map<Long, RawRecord>>();

            for (String storage : persister.storage()) {
                System.out.println("Storage " + storage);
                persister.loadByStorage(storage, new PersistenceProvider.LoadCallback() {
                    @Override
                    public void process(RawRecord record) {
                        Map<Long, RawRecord> unitList = units.get(record.getUnitName());
                        if (unitList == null) {
                            unitList = new HashMap<Long, RawRecord>();
                            units.put(record.getUnitName(), unitList);
                        }
                        unitList.put(record.getId(), record);
                    }
                });

                for (final Map.Entry<String, Map<Long, RawRecord>> unit : units.entrySet()) {
                    BackupFile file = null;
                    for (int i = 0, n = files.size(); i < n; i++)
                        if (BackupFile.isBackup(files.get(i), unit.getKey())) {
                            file = new BackupFile(files.get(i));
                            files.remove(i);
                            break;
                        }

                    if (file == null)
                        throw new RuntimeException("Could not find backup file for unit " + unit.getKey());

                    final Long[] count = new Long[] { 0L };
                    file.read(new PersistenceProvider.LoadCallback() {
                        @Override
                        public void process(RawRecord record) {
                            RawRecord r = unit.getValue().get(record.getId());
                            if (r == null)
                                throw new RuntimeException("Could not find persisted record " + record.getId()
                                        + " for unit " + unit.getKey());
                            if (!r.equals(record))
                                throw new RuntimeException(
                                        "Record " + record.getId() + " mismatch for unit " + unit.getKey());
                            count[0] = count[0] + 1;
                        }
                    });

                    if (count[0] != unit.getValue().size())
                        throw new RuntimeException("Extra persisted records for unit " + unit.getKey());
                    System.out.println("   Unit " + unit.getKey() + ": OK");
                }

                units.clear();
            }

            if (!files.isEmpty()) {
                System.err.println("Extra backups: ");
                for (File file : files)
                    System.err.println("   " + file.getName());
            }
        } else {
            persister.init();
            for (File file : files) {
                InMemoryDatabase.readBackupFile(file, persister);
                System.out.println("Loaded " + file.getName());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        ctx.close();
    }
}

From source file:com.jdom.word.playdough.model.gamepack.GamePackFileGenerator.java

/**
 * Usage: java GamePackFileGenerator <input file> <output directory>
 * /*from w  ww.j  av a2  s . com*/
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    File dictionaryFile = new File(args[0]);

    // Validate arguments first
    if (!dictionaryFile.isFile()) {
        throw new IllegalArgumentException("The specified file does not seem to be a valid file ["
                + dictionaryFile.getAbsolutePath() + "]!");
    }

    File outputDir = new File(args[1]);
    if (!outputDir.isDirectory()) {
        throw new IllegalArgumentException("The specified directory does not seem to be a valid directory ["
                + outputDir.getAbsolutePath() + "]!");
    }

    Set<String> words = GamePackFileGenerator.readWordsFromDictionaryFile(dictionaryFile);

    GamePackFileGenerator generator = new GamePackFileGenerator(words);
    List<Properties> properties = generator.generateGamePacks(20);

    for (int i = 0; i < properties.size(); i++) {
        Properties current = properties.get(i);
        File outputFile = new File(outputDir, i + ".properties");
        PropertiesUtil.writePropertiesFile(current, outputFile);
    }
}

From source file:com.nubits.nubot.launch.MainLaunch.java

/**
 * Start the NuBot. start if config is valid and other instance is running
 *
 * @param args a list of valid arguments
 *//*  w  ww .j a v  a 2 s  .c  om*/
public static void main(String args[]) {

    Global.sessionPath = "logs" + "/" + Settings.SESSION_LOG + System.currentTimeMillis();
    MDC.put("session", Global.sessionPath);
    LOG.info("defined session path " + Global.sessionPath);

    CommandLine cli = parseArgs(args);

    boolean runGUI = false;
    String configFile;

    boolean defaultCfg = false;
    if (cli.hasOption(CLIOptions.GUI)) {
        runGUI = true;
        LOG.info("Running " + Settings.APP_NAME + " with GUI");

        if (!cli.hasOption(CLIOptions.CFG)) {
            LOG.info("Setting default config file location :" + Settings.DEFAULT_CONFIG_FILE_PATH);
            //Cancel any previously existing file, if any
            File f = new File(Settings.DEFAULT_CONFIG_FILE_PATH);
            if (f.exists() && !f.isDirectory()) {
                LOG.warn("Detected a non-empty configuration file, resetting it to default. "
                        + "Printing existing file content, for reference:\n"
                        + FilesystemUtils.readFromFile(Settings.DEFAULT_CONFIG_FILE_PATH));
                FilesystemUtils.deleteFile(Settings.DEFAULT_CONFIG_FILE_PATH);
            }
            //Create a default file
            SaveOptions.optionsReset(Settings.DEFAULT_CONFIG_FILE_PATH);
            defaultCfg = true;
        }
    }
    if (cli.hasOption(CLIOptions.CFG) || defaultCfg) {
        if (defaultCfg) {
            configFile = Settings.DEFAULT_CONFIG_FILE_PATH;
        } else {
            configFile = cli.getOptionValue(CLIOptions.CFG);
        }

        if (runGUI) {
            SessionManager.setConfigGlobal(configFile, true);
            try {
                UiServer.startUIserver(configFile, defaultCfg);
                Global.createShutDownHook();
            } catch (Exception e) {
                LOG.error("error setting up UI server " + e);
            }

        } else {
            LOG.info("Run NuBot from CLI");
            //set global config
            SessionManager.setConfigGlobal(configFile, false);
            sessionLOG.debug("launch bot");
            try {
                SessionManager.setModeStarting();
                SessionManager.launchBot(Global.options);
                Global.createShutDownHook();
            } catch (NuBotRunException e) {
                exitWithNotice("could not launch bot " + e);
            }
        }

    } else {
        exitWithNotice("Missing " + CLIOptions.CFG + ". run nubot with \n" + CLIOptions.USAGE_STRING);
    }

}

From source file:com.msopentech.odatajclient.engine.performance.PerfTestReporter.java

public static void main(final String[] args) throws Exception {
    // 1. check input directory
    final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports");
    if (!reportdir.isDirectory()) {
        throw new IllegalArgumentException("Expected directory, got " + args[0]);
    }//from w ww  .java2  s.  c  o  m

    // 2. read test data from surefire output
    final File[] xmlReports = reportdir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith("-output.txt");
        }
    });

    final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>();

    for (File xmlReport : xmlReports) {
        final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport));
        try {
            while (reportReader.ready()) {
                String line = reportReader.readLine();
                final String[] parts = line.substring(0, line.indexOf(':')).split("\\.");

                final String testClass = parts[0];
                if (!testData.containsKey(testClass)) {
                    testData.put(testClass, new TreeMap<String, Double>());
                }

                line = reportReader.readLine();

                testData.get(testClass).put(parts[1],
                        Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('['))));
            }
        } finally {
            IOUtils.closeQuietly(reportReader);
        }
    }

    // 3. build XSLX output (from template)
    final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src"
            + File.separator + "test" + File.separator + "resources" + File.separator + XLS));

    for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) {
        final Sheet sheet = workbook.getSheet(entry.getKey());

        int rows = 0;

        for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) {
            final Row row = sheet.createRow(rows++);

            Cell cell = row.createCell(0);
            cell.setCellValue(subentry.getKey());

            cell = row.createCell(1);
            cell.setCellValue(subentry.getValue());
        }
    }

    final FileOutputStream out = new FileOutputStream(
            args[0] + File.separator + "target" + File.separator + XLS);
    try {
        workbook.write(out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.tamingtext.classifier.bayes.ClassifyDocument.java

public static void main(String[] args) {
    log.info("Command-line arguments: " + Arrays.toString(args));

    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option inputOpt = obuilder.withLongName("input").withRequired(true)
            .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create())
            .withDescription("Input file").withShortName("i").create();

    Option modelOpt = obuilder.withLongName("model").withRequired(true)
            .withArgument(abuilder.withName("model").withMinimum(1).withMaximum(1).create())
            .withDescription("Model to use when classifying data").withShortName("m").create();

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();//from   w  ww.  j ava2 s.c  o m

    Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(modelOpt).withOption(helpOpt)
            .create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File inputFile = new File(cmdLine.getValue(inputOpt).toString());

        if (!inputFile.isFile()) {
            throw new IllegalArgumentException(inputFile + " does not exist or is not a file");
        }

        File modelDir = new File(cmdLine.getValue(modelOpt).toString());

        if (!modelDir.isDirectory()) {
            throw new IllegalArgumentException(modelDir + " does not exist or is not a directory");
        }

        BayesParameters p = new BayesParameters();
        p.set("basePath", modelDir.getCanonicalPath());
        Datastore ds = new InMemoryBayesDatastore(p);
        Algorithm a = new BayesAlgorithm();
        ClassifierContext ctx = new ClassifierContext(a, ds);
        ctx.initialize();

        //TODO: make the analyzer configurable
        StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
        TokenStream ts = analyzer.tokenStream(null,
                new InputStreamReader(new FileInputStream(inputFile), "UTF-8"));

        ArrayList<String> tokens = new ArrayList<String>(1000);
        while (ts.incrementToken()) {
            tokens.add(ts.getAttribute(CharTermAttribute.class).toString());
        }
        String[] document = tokens.toArray(new String[tokens.size()]);

        ClassifierResult[] cr = ctx.classifyDocument(document, "unknown", 5);

        for (ClassifierResult r : cr) {
            System.err.println(r.getLabel() + "\t" + r.getScore());
        }
    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
    } catch (IOException e) {
        log.error("IOException", e);
    } catch (InvalidDatastoreException e) {
        log.error("InvalidDataStoreException", e);
    } finally {

    }
}