Example usage for java.util Scanner close

List of usage examples for java.util Scanner close

Introduction

In this page you can find the example usage for java.util Scanner close.

Prototype

public void close() 

Source Link

Document

Closes this scanner.

Usage

From source file:edu.usf.cutr.obascs.OBASCSMain.java

public static void main(String[] args) {

    String logLevel = null;/*  w w w.jav a  2  s  . co m*/
    String outputFilePath = null;
    String inputFilePath = null;
    String spreadSheetId = null;
    Logger logger = Logger.getInstance();

    Options options = CommandLineUtil.createCommandLineOptions();
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        logLevel = CommandLineUtil.getLogLevel(cmd);
        logger.setup(logLevel);
        outputFilePath = CommandLineUtil.getOutputPath(cmd);
        spreadSheetId = CommandLineUtil.getSpreadSheetId(cmd);

        inputFilePath = CommandLineUtil.getInputPath(cmd);
    } catch (ParseException e1) {
        logger.logError(e1);
    } catch (FileNotFoundException e) {
        logger.logError(e);
    }

    Map<String, String> agencyMap = null;
    try {
        agencyMap = FileUtil.readAgencyInformantions(inputFilePath);
    } catch (IOException e1) {
        logger.logError(e1);
    }

    logger.log("Consolidation started...");
    logger.log("Trying as public url");

    ListFeed listFeed = null;
    Boolean authRequired = false;
    try {
        listFeed = SpreadSheetReader.readPublicSpreadSheet(spreadSheetId);
    } catch (IOException e) {
        logger.logError(e);
    } catch (ServiceException e) {
        logger.log("Authentication Required");
        authRequired = true;
    }

    if (listFeed == null && authRequired == true) {
        Scanner scanner = new Scanner(System.in);
        String userName, password;
        logger.log("UserName:");
        userName = scanner.nextLine();
        logger.log("Password:");
        password = scanner.nextLine();
        scanner.close();

        try {
            listFeed = SpreadSheetReader.readPrivateSpreadSheet(userName, password, spreadSheetId);
        } catch (IOException e) {
            logger.logError(e);
        } catch (ServiceException e) {
            logger.logError(e);
        }
    }

    if (listFeed != null) {
        //Creating consolidated stops
        String consolidatedString = FileConsolidator.consolidateFile(listFeed, agencyMap);
        try {
            FileUtil.writeToFile(consolidatedString, outputFilePath);
        } catch (FileNotFoundException e) {
            logger.logError(e);
        }

        //Creating sample stop consolidation script config file
        try {
            String path = ClassLoader.getSystemClassLoader()
                    .getResource(GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE).getPath();
            String configXml = FileUtil.readFile(URLUtil.trimSpace(path));
            configXml = ConfigFileGenerator.generateStopConsolidationScriptConfigFile(configXml, agencyMap);
            path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE;
            FileUtil.writeToFile(configXml, path);
        } catch (IOException e) {
            logger.logError(e);
        }

        //Creating sample real-time config file
        try {
            String path = ClassLoader.getSystemClassLoader()
                    .getResource(GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE).getPath();
            String configXml = FileUtil.readFile(URLUtil.trimSpace(path));
            configXml = ConfigFileGenerator.generateSampleRealTimeConfigFile(configXml, agencyMap);
            path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE;
            FileUtil.writeToFile(configXml, path);
        } catch (IOException e) {
            logger.logError(e);
        }
    } else {
        logger.logError("Cannot write files");
    }

    logger.log("Consolidation finished...");

}

From source file:Main.java

public static void main(String[] args) {

    String s = "java2s.com 1 + 1 = 2.0 true";

    Scanner scanner = new Scanner(s);

    scanner.useLocale(Locale.US);

    while (scanner.hasNext()) {

        // if the next is a double, print found and the double
        if (scanner.hasNextDouble()) {
            System.out.println("Found :" + scanner.nextDouble());
        }/*from  w w w .  j  a va  2  s.  c om*/

        // if a double is not found, print "Not Found" and the token
        System.out.println("Not Found :" + scanner.next());
    }

    scanner.close();
}

From source file:com.joliciel.talismane.terminology.TalismaneTermExtractorMain.java

public static void main(String[] args) throws Exception {
    String termFilePath = null;/*w ww .j  av a2 s  .c o m*/
    String outFilePath = null;
    Command command = Command.extract;
    int depth = -1;
    String databasePropertiesPath = null;
    String projectCode = null;
    String terminologyPropertiesPath = null;

    Map<String, String> argMap = StringUtils.convertArgs(args);

    String logConfigPath = argMap.get("logConfigFile");
    if (logConfigPath != null) {
        argMap.remove("logConfigFile");
        Properties props = new Properties();
        props.load(new FileInputStream(logConfigPath));
        PropertyConfigurator.configure(props);
    }

    Map<String, String> innerArgs = new HashMap<String, String>();
    for (Entry<String, String> argEntry : argMap.entrySet()) {
        String argName = argEntry.getKey();
        String argValue = argEntry.getValue();

        if (argName.equals("command"))
            command = Command.valueOf(argValue);
        else if (argName.equals("termFile"))
            termFilePath = argValue;
        else if (argName.equals("outFile"))
            outFilePath = argValue;
        else if (argName.equals("depth"))
            depth = Integer.parseInt(argValue);
        else if (argName.equals("databaseProperties"))
            databasePropertiesPath = argValue;
        else if (argName.equals("terminologyProperties"))
            terminologyPropertiesPath = argValue;
        else if (argName.equals("projectCode"))
            projectCode = argValue;
        else
            innerArgs.put(argName, argValue);
    }
    if (termFilePath == null && databasePropertiesPath == null)
        throw new TalismaneException("Required argument: termFile or databasePropertiesPath");

    if (termFilePath != null) {
        String currentDirPath = System.getProperty("user.dir");
        File termFileDir = new File(currentDirPath);
        if (termFilePath.lastIndexOf("/") >= 0) {
            String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/"));
            termFileDir = new File(termFileDirPath);
            termFileDir.mkdirs();
        }
    }

    long startTime = new Date().getTime();
    try {
        if (command.equals(Command.analyse)) {
            innerArgs.put("command", "analyse");
        } else {
            innerArgs.put("command", "process");
        }

        String sessionId = "";
        TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId);
        TalismaneService talismaneService = locator.getTalismaneService();

        TalismaneConfig config = talismaneService.getTalismaneConfig(innerArgs, sessionId);

        TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance(locator);
        TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService();
        TerminologyBase terminologyBase = null;

        if (projectCode == null)
            throw new TalismaneException("Required argument: projectCode");

        File file = new File(databasePropertiesPath);
        FileInputStream fis = new FileInputStream(file);
        Properties dataSourceProperties = new Properties();
        dataSourceProperties.load(fis);
        terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties);

        TalismaneSession talismaneSession = talismaneService.getTalismaneSession();

        if (command.equals(Command.analyse) || command.equals(Command.extract)) {
            Locale locale = talismaneSession.getLocale();
            Map<TerminologyProperty, String> terminologyProperties = new HashMap<TerminologyProperty, String>();
            if (terminologyPropertiesPath != null) {
                Map<String, String> terminologyPropertiesStr = StringUtils.getArgMap(terminologyPropertiesPath);
                for (String key : terminologyPropertiesStr.keySet()) {
                    try {
                        TerminologyProperty property = TerminologyProperty.valueOf(key);
                        terminologyProperties.put(property, terminologyPropertiesStr.get(key));
                    } catch (IllegalArgumentException e) {
                        throw new TalismaneException("Unknown terminology property: " + key);
                    }
                }
            } else {
                terminologyProperties = getDefaultTerminologyProperties(locale);
            }
            if (depth <= 0 && !terminologyProperties.containsKey(TerminologyProperty.maxDepth))
                throw new TalismaneException("Required argument: depth");

            InputStream regexInputStream = getInputStreamFromResource(
                    "parser_conll_with_location_input_regex.txt");
            Scanner regexScanner = new Scanner(regexInputStream, "UTF-8");
            String inputRegex = regexScanner.nextLine();
            regexScanner.close();
            config.setInputRegex(inputRegex);

            Charset outputCharset = config.getOutputCharset();

            TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase,
                    terminologyProperties);
            if (depth > 0)
                termExtractor.setMaxDepth(depth);
            termExtractor.setOutFilePath(termFilePath);

            if (outFilePath != null) {
                if (outFilePath.lastIndexOf("/") >= 0) {
                    String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/"));
                    File outFileDir = new File(outFileDirPath);
                    outFileDir.mkdirs();
                }
                File outFile = new File(outFilePath);
                outFile.delete();
                outFile.createNewFile();

                Writer writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset));
                TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer);
                termExtractor.addTermObserver(termAnalysisWriter);
            }

            Talismane talismane = config.getTalismane();
            talismane.setParseConfigurationProcessor(termExtractor);
            talismane.process();
        } else if (command.equals(Command.list)) {

            List<Term> terms = terminologyBase.findTerms(2, null, 0, null, null);
            for (Term term : terms) {
                LOG.debug("Term: " + term.getText());
                LOG.debug("Frequency: " + term.getFrequency());
                LOG.debug("Heads: " + term.getHeads());
                LOG.debug("Expansions: " + term.getExpansions());
                LOG.debug("Contexts: " + term.getContexts());
            }
        }
    } finally {
        long endTime = new Date().getTime();
        long totalTime = endTime - startTime;
        LOG.info("Total time: " + totalTime);
    }
}

From source file:de.dakror.scpuller.SCPuller.java

public static void main(String[] args) {
    new File(System.getProperty("user.home") + "/.dakror/SCPuller").mkdirs();
    new File(System.getProperty("user.home") + "/.dakror/SCPuller/download").mkdir();
    Scanner scanner = new Scanner(System.in);

    loadDownloadedSongs();// w w  w. j  av  a  2 s . c  o m

    try {
        while (true) {
            String line = scanner.nextLine().trim();
            download(line);

            saveDownloadedSongs();
        }
    } finally {
        scanner.close();
    }
}

From source file:bundestagswahl.benchmark.BWBenchmark.java

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

    resultTime = new double[6];

    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter URL: ");
    serverUrl = scanner.nextLine();//from w w w  .  j  a v a2s . c o m
    System.out.print("Please enter number of terminals: ");
    numberTerminals = scanner.nextInt();
    System.out.print("Please enter number of requests: ");
    numberRequests = scanner.nextInt();
    System.out.print("Please enter delay between two requests in seconds: ");
    requestDelay = scanner.nextDouble();
    scanner.close();

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(numberTerminals);
    HttpClient httpclient = new DefaultHttpClient(cm);
    httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 300000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 300000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    try {
        final CountDownLatch latch = new CountDownLatch(numberTerminals);
        for (int i = 0; i < numberTerminals; i++) {
            BenchmarkTerminal terminal = new BenchmarkTerminal(httpclient, latch, serverUrl, numberRequests,
                    requestDelay);
            terminal.start();
        }
        latch.await();
        httpclient.getConnectionManager().shutdown();
    } finally {

    }

    printResultTimes();
    System.out.println(" ");
    System.out.println("Done");
}

From source file:IMAPService.java

public static void main(String[] args) {
    // Arguments//  w  w  w.java 2s  . co m
    String server = "";
    int port = -1;
    String login = "";
    String password = "";
    boolean deleteAfterDownload = false;
    boolean downloadAll = false;
    String[] foldersToDownload = null;

    // Set up apache cli
    Options options = new Options();

    Option S = new Option("S", true, "Server Name");
    S.setRequired(true);
    options.addOption(S);

    Option P = new Option("P", true, "Port Number");
    P.setRequired(true);
    options.addOption(P);

    Option l = new Option("l", true, "Login");
    l.setRequired(true);
    options.addOption(l);

    Option p = new Option("p", true, "Password if not on stdin");
    options.addOption(p);

    Option d = new Option("d", false, "Delete after downloading");
    d.setRequired(false);
    options.addOption(d);

    Option a = new Option("a", false, "Download from all folders");
    a.setRequired(false);
    options.addOption(a);

    Option f = new Option("f", true, "Download messages from specified folder");
    options.addOption(f);

    CommandLineParser clp = new DefaultParser();

    try {
        CommandLine cl = clp.parse(options, args);

        if (cl.hasOption("S"))
            server = cl.getOptionValue("S");

        if (cl.hasOption("P"))
            port = Integer.parseInt(cl.getOptionValue("P"));

        if (cl.hasOption("l"))
            login = cl.getOptionValue("l");

        if (cl.hasOption("p"))
            password = cl.getOptionValue("p");

        if (cl.hasOption("d"))
            deleteAfterDownload = true;

        if (cl.hasOption("a"))
            downloadAll = true;
        else if (cl.hasOption("f"))
            foldersToDownload = cl.getOptionValues("f");
        else {
            showArgMenu(options);
            return;
        }

    } catch (Exception e) {
        showArgMenu(options);
        return;
    }

    if (password.isEmpty()) {
        // Grab p/w of stdin if it's there
        Scanner sc = new Scanner(System.in);

        password = sc.nextLine();

        sc.close();
    }

    if (!server.isEmpty() && port != -1 && !login.isEmpty() && !password.isEmpty()
            && (downloadAll || foldersToDownload != null)) {
        //IMAPService imapService = new IMAPService("imap.gmail.com", 993);
        IMAPService imapService = new IMAPService(server, port);
        //imapService.login("kinglibingli@gmail.com", "kingli1bingli");
        imapService.login(login, password);
        imapService.buildMailbox();
        // Check if service should delete emails
        if (deleteAfterDownload)
            imapService.deleteEmailsAfterDownload();
        // Proceed with downloads
        if (downloadAll)
            imapService.downloadAllFolders();
        else {
            for (String folderNames : foldersToDownload) {
                imapService.downloadFoldersEmails(folderNames);
            }
        }

        imapService.logout();
    }

}

From source file:de.prozesskraft.ptest.Fingerprint.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try/*from  w w  w. jav  a  2 s. c  o m*/
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Fingerprint.class) + "/" + "../etc/ptest-fingerprint.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option opath = OptionBuilder.withArgName("PATH").hasArg()
            .withDescription(
                    "[mandatory; default: .] the root path for the tree you want to make a fingerprint from.")
            //            .isRequired()
            .create("path");

    Option osizetol = OptionBuilder.withArgName("FLOAT").hasArg().withDescription(
            "[optional; default: 0.02] the sizeTolerance (as factor in percent) of all file entries will be set to this value. [0.0 < sizetol < 1.0]")
            //            .isRequired()
            .create("sizetol");

    Option omd5 = OptionBuilder.withArgName("no|yes").hasArg()
            .withDescription("[optional; default: yes] should be the md5sum of files determined? no|yes")
            //            .isRequired()
            .create("md5");

    Option oignore = OptionBuilder.withArgName("STRING").hasArgs()
            .withDescription("[optional] path-pattern that should be ignored when creating the fingerprint")
            //            .isRequired()
            .create("ignore");

    Option oignorefile = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[optional] file with path-patterns (one per line) that should be ignored when creating the fingerprint")
            //            .isRequired()
            .create("ignorefile");

    Option ooutput = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory; default: <path>/fingerprint.xml] fingerprint file")
            //            .isRequired()
            .create("output");

    Option of = new Option("f", "[optional] force overwrite fingerprint file if it already exists");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(opath);
    options.addOption(osizetol);
    options.addOption(omd5);
    options.addOption(oignore);
    options.addOption(oignorefile);
    options.addOption(ooutput);
    options.addOption(of);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);

    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingerprint", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     " + web);
        System.out.println("author: " + author);
        System.out.println("version:" + version);
        System.out.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    String path = "";
    String sizetol = "";
    boolean md5 = false;
    Float sizetolFloat = null;
    String output = "";
    java.io.File ignorefile = null;
    ArrayList<String> ignore = new ArrayList<String>();

    if (!(commandline.hasOption("path"))) {
        System.err.println("setting default for -path=.");
        path = ".";
    } else {
        path = commandline.getOptionValue("path");
    }

    if (!(commandline.hasOption("sizetol"))) {
        System.err.println("setting default for -sizetol=0.02");
        sizetol = "0.02";
        sizetolFloat = 0.02F;
    } else {
        sizetol = commandline.getOptionValue("sizetol");
        sizetolFloat = Float.parseFloat(sizetol);

        if ((sizetolFloat > 1) || (sizetolFloat < 0)) {
            System.err.println("use only values >=0.0 and <1.0 for -sizetol");
            System.exit(1);
        }
    }

    if (!(commandline.hasOption("md5"))) {
        System.err.println("setting default for -md5=yes");
        md5 = true;
    } else if (commandline.getOptionValue("md5").equals("no")) {
        md5 = false;
    } else if (commandline.getOptionValue("md5").equals("yes")) {
        md5 = true;
    } else {
        System.err.println("use only values no|yes for -md5");
        System.exit(1);
    }

    if (commandline.hasOption("ignore")) {
        ignore.addAll(Arrays.asList(commandline.getOptionValues("ignore")));
    }

    if (commandline.hasOption("ignorefile")) {
        ignorefile = new java.io.File(commandline.getOptionValue("ignorefile"));
        if (!ignorefile.exists()) {
            System.err.println("warn: ignore file does not exist: " + ignorefile.getCanonicalPath());
        }
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("setting default for -output=" + path + "/fingerprint.xml");
        output = path + "/fingerprint.xml";
    } else {
        output = commandline.getOptionValue("output");
    }

    // wenn output bereits existiert -> abbruch
    java.io.File outputFile = new File(output);
    if (outputFile.exists()) {
        if (commandline.hasOption("f")) {
            outputFile.delete();
        } else {
            System.err
                    .println("error: output file (" + output + ") already exists. use -f to force overwrite.");
            System.exit(1);
        }
    }

    //      if ( !( commandline.hasOption("output")) )
    //      {
    //         System.err.println("option -output is mandatory.");
    //         exiter();
    //      }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Dir dir = new Dir();
    dir.setBasepath(path);
    dir.setOutfilexml(output);

    // ignore file in ein Array lesen
    if ((ignorefile != null) && (ignorefile.exists())) {
        Scanner sc = new Scanner(ignorefile);
        while (sc.hasNextLine()) {
            ignore.add(sc.nextLine());
        }
        sc.close();
    }

    //      // autoignore hinzufuegen
    //      String autoIgnoreString = ini.get("autoignore", "autoignore");
    //      ignoreLines.addAll(Arrays.asList(autoIgnoreString.split(",")));

    //      // debug
    //      System.out.println("ignorefile content:");
    //      for(String actLine : ignore)
    //      {
    //         System.out.println("line: "+actLine);
    //      }

    try {
        dir.genFingerprint(sizetolFloat, md5, ignore);
    } catch (NullPointerException e) {
        System.err.println("file/dir does not exist " + path);
        e.printStackTrace();
        exiter();
    } catch (IOException e) {
        e.printStackTrace();
        exiter();
    }

    System.out.println("writing to file: " + dir.getOutfilexml());
    dir.writeXml();

}

From source file:se.berazy.api.examples.App.java

/**
 * Operation examples.// w  w w.  j  a  v a  2s  .  co m
 * @param args
 */
public static void main(String[] args) {
    Scanner scanner = null;
    try {
        client = new BookkeepingClient();
        System.out.println("Choose operation to invoke:\n");
        System.out.println("1. Create invoice");
        System.out.println("2. Credit invoice");
        scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            line = (line != null) ? line.trim().toLowerCase() : "";
            if (line.equals("1")) {
                outPutResponse(createInvoice());
            } else if (line.equals("2")) {
                outPutResponse(creditInvoice());
            } else if (line.equals("q") || line.equals("quit") || line.equals("exit")) {
                System.exit(0);
            } else {
                System.out.println("\nPlease choose an operation from 1-7.");
            }
        }
        scanner.close();
    } catch (Exception ex) {
        System.out.println(String.format(
                "\nAn exception occured, press CTRL+C to exit or enter 'q', 'quit' or 'exit'.\n\nException: %s %s",
                ex.getMessage(), ex.getStackTrace()));
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

From source file:languages.TabFile.java

public static void main(String[] args) {
    if (args[0].equals("optimize")) {
        Scanner sc = new Scanner(System.in);
        String targetPath;/*from   ww w  . java2 s.  co m*/
        String originPath;

        System.out.println("Please enter the path of the original *.tab-files:");

        originPath = sc.nextLine();

        System.out.println(
                "Please enter the path where you wish to save the optimized *.tab-files (Directories will be created, existing files with same filenames will be overwritten):");

        targetPath = sc.nextLine();

        sc.close();

        File folder = new File(originPath);
        File[] listOfFiles = folder.listFiles();

        assert listOfFiles != null;
        for (File file : listOfFiles) {
            if (!file.getName().equals("LICENSE")) {
                TabFile origin;
                try {
                    String originFileName = file.getAbsolutePath();
                    System.out.print("Reading file '" + originFileName + "'...");
                    origin = new TabFile(originFileName);
                    System.out.println("Done!");
                    System.out.print("Optimizing file...");
                    TabFile res = TabFile.optimizeDictionaries(origin, 2, true);
                    System.out.println("Done!");

                    String targetFileName = targetPath + File.separator + file.getName();

                    System.out.println("Saving new file as '" + targetFileName + "'...");
                    res.save(targetFileName);
                    System.out.println("Done!");
                } catch (IOException e) {
                    FOKLogger.log(TabFile.class.getName(), Level.SEVERE, "An error occurred", e);
                }
            }
        }
    } else if (args[0].equals("merge")) {
        System.err.println(
                "Merging dictionaries is not supported anymore. Please checkout commit 1a6fa16 to merge dictionaries.");
    }
}

From source file:carmen.demo.LocationResolverDemo.java

public static void main(String[] args)
        throws ParseException, FileNotFoundException, IOException, ClassNotFoundException {
    // Parse the command line.
    String[] manditory_args = { "input_file" };
    createCommandLineOptions();/*from  w  ww  . ja va  2s .  c  o  m*/
    CommandLineUtilities.initCommandLineParameters(args, LocationResolverDemo.options, manditory_args);

    // Get options
    String inputFile = CommandLineUtilities.getOptionValue("input_file");
    String outputFile = null;
    if (CommandLineUtilities.hasArg("output_file")) {
        outputFile = CommandLineUtilities.getOptionValue("output_file");
    }

    logger.info("Creating LocationResolver.");
    LocationResolver resolver = LocationResolver.getLocationResolver();

    Scanner scanner = Utils.createScanner(inputFile);

    Writer writer = null;
    if (outputFile != null) {
        writer = Utils.createWriter(outputFile);
        logger.info("Saving geolocated tweets to: " + outputFile);
    }
    ObjectMapper mapper = new ObjectMapper();
    int numResolved = 0;
    int total = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        @SuppressWarnings("unchecked")
        HashMap<String, Object> tweet = (HashMap<String, Object>) mapper.readValue(line, Map.class);

        total++;
        Location location = resolver.resolveLocationFromTweet(tweet);

        if (location != null) {
            logger.debug("Found location: " + location.toString());
            numResolved++;
        }
        if (writer != null) {
            if (location != null) {
                tweet.put("location", Location.createJsonFromLocation(location));
            }
            mapper.writeValue(writer, tweet);
            writer.write("\n");
        }

    }
    scanner.close();
    if (writer != null)
        writer.close();

    logger.info("Resolved locations for " + numResolved + " of " + total + " tweets.");
}