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:com.joliciel.talismane.machineLearning.perceptron.PerceptronClassifactionModelTrainerImpl.java

void prepareData(ClassificationEventStream eventStream) {
    try {//from w w  w  .  j a va  2  s . c o m
        eventFile = File.createTempFile("events", "txt");
        eventFile.deleteOnExit();
        Writer eventWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(eventFile), "UTF-8"));
        while (eventStream.hasNext()) {
            ClassificationEvent corpusEvent = eventStream.next();
            PerceptronEvent event = new PerceptronEvent(corpusEvent, params);
            event.write(eventWriter);
        }
        eventWriter.flush();
        eventWriter.close();

        if (cutoff > 1) {
            params.initialiseCounts();
            File originalEventFile = eventFile;
            Scanner scanner = new Scanner(
                    new BufferedReader(new InputStreamReader(new FileInputStream(eventFile), "UTF-8")));

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                PerceptronEvent event = new PerceptronEvent(line);
                for (int featureIndex : event.getFeatureIndexes()) {
                    params.getFeatureCounts()[featureIndex]++;
                }
            }
            scanner.close();

            if (LOG.isDebugEnabled()) {
                int[] cutoffCounts = new int[21];
                for (int count : params.getFeatureCounts()) {
                    for (int i = 1; i < 21; i++) {
                        if (count >= i) {
                            cutoffCounts[i]++;
                        }
                    }
                }
                LOG.debug("Feature counts:");
                for (int i = 1; i < 21; i++) {
                    LOG.debug("Cutoff " + i + ": " + cutoffCounts[i]);
                }
            }
            PerceptronModelParameters cutoffParams = new PerceptronModelParameters();
            int[] newIndexes = cutoffParams.initialise(params, cutoff);
            decisionMaker = new PerceptronDecisionMaker<T>(cutoffParams, decisionFactory);
            scanner = new Scanner(
                    new BufferedReader(new InputStreamReader(new FileInputStream(eventFile), "UTF-8")));

            eventFile = File.createTempFile("eventsCutoff", "txt");
            eventFile.deleteOnExit();
            Writer eventCutoffWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(eventFile), "UTF-8"));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                PerceptronEvent oldEvent = new PerceptronEvent(line);
                PerceptronEvent newEvent = new PerceptronEvent(oldEvent, newIndexes);
                newEvent.write(eventCutoffWriter);
            }
            eventCutoffWriter.flush();
            eventCutoffWriter.close();
            params = cutoffParams;
            originalEventFile.delete();
        }

        params.initialiseWeights();
        totalFeatureWeights = new double[params.getFeatureCount()][params.getOutcomeCount()];
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:magixcel.Main.java

private static void setup() {
    Scanner s = new Scanner(System.in);
    boolean doContinue = false;

    //        Intro
    printLogo();/*from ww w. ja v  a  2  s .c  o  m*/
    System.out.println("Welcome to MagiXcel");
    System.out.println("Current encoding is " + Charset.defaultCharset());

    //        Table name
    while (!doContinue) {
        System.out.println("Type your desired table name:");
        if (s.hasNextLine()) {
            Table.setTableName(s.nextLine());
        }

        doContinue = isThisOk(s);
    }
    doContinue = false;

    //        File path
    String path = "";
    while (!doContinue) {
        System.out.println("Enter FULL path of .csv or .txt file you wish to convert");
        if (s.hasNextLine()) {
            path = StringEscapeUtils.escapeJava(s.nextLine());
        }
        FileMan.setPath(path);
        if (FileMan.currentPathIsValid()) {
            doContinue = isThisOk(s);
        } else {
            System.out.println("ERROR: Invalid Path");
            doContinue = false;
        }

    }
    doContinue = false;

    //        File setup
    FileMan.getLinesFromFile();
    Table.setColumnNames(FileMan.takeFirstRow());
    FileMan.addRowsToTable();

    //        Choose output mode
    System.out.println("Choose output mode:");
    OutputFormat.printOutputOptionsNumbered();
    int selectedOption = -1;
    while (!doContinue) {
        if (s.hasNextLine()) {
            selectedOption = Integer.parseInt(s.nextLine());
        }
        doContinue = OutputFormat.chooseOption(selectedOption, s);
    }

    doContinue = false;
    OutputFormat.format();

    FileMan.writeToFile();

    System.out.println("Thank you for using MagiXcel!");
    System.out.println("Press Enter to exit");
    s.nextLine();
    s.close();

}

From source file:edu.brandeis.cs.develops.eptosql.Cli.java

public void parse() throws IOException {
    CommandLineParser parser = new BasicParser();

    CodeGenerationOption cgo = CodeGenerationOption.UNNESTED;
    IROption iro = IROption.ENABLE;//from   w  ww.  j a  va2 s.c  o  m
    CommandLine cmd = null;
    Scanner sc = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (cmd.hasOption("h"))
        help();
    if (cmd.hasOption("nested"))
        cgo = CodeGenerationOption.NESTED;
    if (cmd.hasOption("disable_ir"))
        iro = IROption.DISABLE;
    if (cmd.hasOption("f")) {
        //log.log(Level.INFO, "Using cli argument -f=" + cmd.getOptionValue("f"));
        String filename = cmd.getOptionValue("f");
        sc = new Scanner(new File(filename));
    } else {
        sc = new Scanner(System.in);
    }
    String plan;
    while ((sc.hasNextLine())) {
        plan = sc.nextLine().trim();
        if (plan.length() == 0)
            continue;
        System.out.println(EPtoSQL.syncCompile(cgo, iro, plan));
    }
    sc.close();
}

From source file:com.gitblit.auth.HtpasswdAuthProvider.java

/**
 * Reads the realm file and rebuilds the in-memory lookup tables.
 *//*  w  ww.j a va2 s .  c  om*/
protected synchronized void read() {
    boolean forceReload = false;
    File file = getFileOrFolder(KEY_HTPASSWD_FILE, DEFAULT_HTPASSWD_FILE);
    if (!file.equals(htpasswdFile)) {
        this.htpasswdFile = file;
        this.htUsers.clear();
        forceReload = true;
    }

    if (htpasswdFile.exists() && (forceReload || (htpasswdFile.lastModified() != lastModified))) {
        lastModified = htpasswdFile.lastModified();
        htUsers.clear();

        Pattern entry = Pattern.compile("^([^:]+):(.+)");

        Scanner scanner = null;
        try {
            scanner = new Scanner(new FileInputStream(htpasswdFile));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                if (!line.isEmpty() && !line.startsWith("#")) {
                    Matcher m = entry.matcher(line);
                    if (m.matches()) {
                        htUsers.put(m.group(1), m.group(2));
                    }
                }
            }
        } catch (Exception e) {
            logger.error(MessageFormat.format("Failed to read {0}", htpasswdFile), e);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }
}

From source file:net.pms.medialibrary.commons.helpers.FileImportHelper.java

/**
 * Cleans the received fileName according to the rules defined in filename_replace_expressions.txt
 * @param fileName the name to clean// w  ww . j  a  v a 2  s . c om
 * @return the cleaned name
 */
private static String getCleanName(String fileName) {
    File configFile = new File(FilenameUtils.concat(PMS.getConfiguration().getProfileDirectory(),
            "filename_replace_expressions.txt"));

    String res = fileName;
    Scanner scanner = null;
    try {
        scanner = new Scanner(new FileInputStream(configFile.getAbsolutePath()), "UTF-8");
        String regex;
        String replaceText;
        while (scanner.hasNextLine()) {
            regex = scanner.nextLine();
            if (scanner.hasNextLine()) {
                replaceText = scanner.nextLine();
            } else {
                break;
            }
            res = res.replaceAll(regex, replaceText);
        }
    } catch (FileNotFoundException e) {
        if (log.isDebugEnabled())
            log.debug(String.format("File '%s' not found. Ignore file name cleaning",
                    configFile.getAbsolutePath()));
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }

    res = res.trim();
    if (!res.equals(fileName)) {
        if (log.isInfoEnabled())
            log.info(String.format("Cleaned up file '%s' to '%s'", fileName, res));
    }
    return res;
}

From source file:UniqueInstance.java

/**
 * Reoit un message d'une socket s'tant connecte au serveur d'coute. Si ce message est le message de l'instance
 * unique, l'application demande le focus.
 *
 * @param socket/*  w w w  . java 2 s.  co m*/
 * Socket connect au serveur d'coute.
 */
private void receive(Socket socket) {
    Scanner sc = null;

    try {
        /* On n'coute que 5 secondes, si aucun message n'est reu, tant pis... */
        socket.setSoTimeout(5000);

        /* On dfinit un Scanner pour lire sur l'entre de la socket. */
        sc = new Scanner(socket.getInputStream());

        /* On ne lit qu'une ligne. */
        String s = sc.nextLine();

        /* Si cette ligne est le message de l'instance unique... */
        if (message.equals(s)) {
            /* On excute le code demand. */
            runOnReceive.run();
        }
    } catch (IOException e) {
        Logger.getLogger("UniqueInstance").warning("Lecture du flux d'entre de la socket chou.");
    } finally {
        if (sc != null) {
            sc.close();
        }
    }

}

From source file:dtv.controller.FXMLMainController.java

private String getPreferences() throws Exception {

    if (filePrefs != null && filePrefs.canRead()) {
        Scanner scanner = new Scanner(filePrefs);
        String line;//ww w .  j av  a  2  s  . com

        while (scanner.hasNext()) {
            line = scanner.nextLine();
            if (line.contains(FAV_TAG)) {
                String preferences = line.substring(1 + line.indexOf(">"), line.lastIndexOf("<"));
                Utils.prefTab = preferences.split(Utils.FAV_SEP);
                break;
            }
        }

        scanner.close();

    } else {
        Utils.prefTab = Utils.PPREFS;
    }

    return Utils.getPreferences();
}

From source file:com.alibaba.dubbo.qos.textui.TTree.java

@Override
public String rendering() {

    final StringBuilder treeSB = new StringBuilder();
    recursive(0, true, "", root, new Callback() {

        @Override/*from  w w w.  ja  v a2 s. c  o  m*/
        public void callback(int deep, boolean isLast, String prefix, Node node) {

            final boolean hasChild = !node.children.isEmpty();
            final String stepString = isLast ? STEP_FIRST_CHAR : STEP_NORMAL_CHAR;
            final int stepStringLength = StringUtils.length(stepString);
            treeSB.append(prefix).append(stepString);

            int costPrefixLength = 0;
            if (hasChild) {
                treeSB.append("+");
            }
            if (isPrintCost && !node.isRoot()) {
                final String costPrefix = String.format("[%s,%sms]", (node.endTimestamp - root.beginTimestamp),
                        (node.endTimestamp - node.beginTimestamp));
                costPrefixLength = StringUtils.length(costPrefix);
                treeSB.append(costPrefix);
            }

            final Scanner scanner = new Scanner(new StringReader(node.data.toString()));
            try {
                boolean isFirst = true;
                while (scanner.hasNextLine()) {
                    if (isFirst) {
                        treeSB.append(scanner.nextLine()).append("\n");
                        isFirst = false;
                    } else {
                        treeSB.append(prefix).append(repeat(' ', stepStringLength))
                                .append(hasChild ? "|" : EMPTY).append(repeat(' ', costPrefixLength))
                                .append(scanner.nextLine()).append("\n");
                    }
                }
            } finally {
                scanner.close();
            }

        }

    });

    return treeSB.toString();
}

From source file:com.rockhoppertech.music.scale.Scale.java

/**
 * @param name// w  w w.ja v  a 2  s  .  c o m
 *            the name to set
 */
public void setName(final String name) {
    if (name.contains(",")) {
        Scanner s = new Scanner(name);
        s.useDelimiter(",");
        this.name = s.next();
        while (s.hasNext()) {
            aliases.add(s.next());
        }
        s.close();
    } else {
        this.name = name;
    }
}

From source file:com.joliciel.jochre.lexicon.TextFileLexicon.java

public TextFileLexicon(File textFile, String charset) {
    Scanner scanner;
    try {/* w  w  w  . j a  v a2s  . c  o  m*/
        scanner = new Scanner(
                new BufferedReader(new InputStreamReader(new FileInputStream(textFile), charset)));

        try {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (!line.startsWith("#")) {
                    String[] parts = line.split("\t");

                    if (parts.length > 0) {
                        String word = parts[0];
                        int frequency = 1;
                        if (parts.length > 1)
                            frequency = Integer.parseInt(parts[1]);
                        entries.put(word, frequency);
                    }

                }

            }
        } finally {
            scanner.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}