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:tr.edu.gsu.nerwip.recognition.internal.modelless.subee.Subee.java

/**
 * Loads the list of demonyms. It is supposed to contain only
 * unambiguous demonyms, i.e. strings which are not at the same
 * time the adjective and the name of the place. We want to keep
 * locations./*from  w w  w  .j a  v  a  2  s .co  m*/
 */
private synchronized void loadDemonyms() {
    if (DEMONYMS.isEmpty()) {
        logger.log("Loading demonyms");
        logger.increaseOffset();

        // set up file path
        String path = FileNames.FO_CUSTOM_LISTS + File.separator + FileNames.FI_DEMONYMS;
        File file = new File(path);

        // retrieve demonyms
        try {
            Scanner scanner = FileTools.openTextFileRead(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                DEMONYMS.add(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        logger.decreaseOffset();
        logger.log("Loading complete");
    }
}

From source file:tr.edu.gsu.nerwip.recognition.internal.modelless.subee.Subee.java

/**
 * Loads the existing list of unknown Freebase types.
 * This list is supposed to be processed manually,
 * in order to complete the other FB-related files of
 * Subee. The goal is to associate an EntityType value
 * to all FB types.// w  ww .  j  a  v a  2 s .co m
 */
private synchronized void loadUnknownTypes() {
    if (UNKNOWN_TYPES.isEmpty()) {
        logger.log("Loading unknown Freebase types");
        logger.increaseOffset();

        // set up file path
        String path = FileNames.FO_SUBEE + File.separator + FileNames.FI_UNKNOWN_TYPES;
        File file = new File(path);

        // retrieve existing unknown types
        try {
            Scanner scanner = FileTools.openTextFileRead(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                UNKNOWN_TYPES.add(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        logger.decreaseOffset();
        logger.log("Loading complete");
    }
}

From source file:com.knowprocess.bpm.bdd.BpmSpec.java

protected String getJson(String messageResource) {
    InputStream is = null;//w  ww . j av a  2s.  c o  m
    Reader source = null;
    Scanner scanner = null;
    String json = null;
    try {
        is = getClass().getResourceAsStream(messageResource);
        // assertNotNull("Unable to load test resource: " + messageResource,
        // is);
        source = new InputStreamReader(is);
        scanner = new Scanner(source);
        json = scanner.useDelimiter("\\A").next();
    } catch (NullPointerException e) {
        // assume message supplied directly
        json = messageResource;
    } finally {
        try {
            scanner.close();
        } catch (Exception e) {
            ;
        }
    }
    return json;
}

From source file:edu.ucuenca.authorsdisambiguation.Distance.java

public synchronized String Http(String s) throws SQLException, IOException {

    Statement stmt = conn.createStatement();
    String sql;//from w  w w.  j a  v  a  2 s.  c  o  m
    sql = "SELECT * FROM cache where cache.key='" + getMD5(s) + "'";
    java.sql.ResultSet rs = stmt.executeQuery(sql);
    String resp = "";
    if (rs.next()) {
        resp = rs.getString("value");
        rs.close();
        stmt.close();
    } else {
        rs.close();
        stmt.close();
        final URL url = new URL(s);
        final URLConnection connection = url.openConnection();
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
        connection.addRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
        while (reader.hasNextLine()) {
            final String line = reader.nextLine();
            resp += line + "\n";
        }
        reader.close();

        try {
            JsonParser parser = new JsonParser();
            parser.parse(resp);
            PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)");
            stmt2.setString(1, getMD5(s));
            stmt2.setString(2, resp);
            stmt2.executeUpdate();
            stmt2.close();
        } catch (Exception e) {
            System.out.printf("Error al insertar en la DB: " + e);
        }

    }

    return resp;
}

From source file:edu.ucuenca.authorsdisambiguation.Distance.java

public synchronized String Http2(String s, Map<String, String> mp) throws SQLException, IOException {
    String md = s + mp.toString();
    Statement stmt = conn.createStatement();
    String sql;/*from w  ww  . ja v a 2s. c om*/
    sql = "SELECT * FROM cache where cache.key='" + getMD5(md) + "'";
    java.sql.ResultSet rs = stmt.executeQuery(sql);
    String resp = "";
    if (rs.next()) {
        resp = rs.getString("value");
        rs.close();
        stmt.close();
    } else {
        rs.close();
        stmt.close();

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(s);

        //Add any parameter if u want to send it with Post req.
        for (Entry<String, String> mcc : mp.entrySet()) {
            method.addParameter(mcc.getKey(), mcc.getValue());
        }

        int statusCode = client.executeMethod(method);

        if (statusCode != -1) {
            InputStream in = method.getResponseBodyAsStream();
            final Scanner reader = new Scanner(in, "UTF-8");
            while (reader.hasNextLine()) {
                final String line = reader.nextLine();
                resp += line + "\n";
            }
            reader.close();

            try {
                JsonParser parser = new JsonParser();
                parser.parse(resp);
                PreparedStatement stmt2 = conn.prepareStatement("INSERT INTO cache (key, value) values (?, ?)");
                stmt2.setString(1, getMD5(md));
                stmt2.setString(2, resp);
                stmt2.executeUpdate();
                stmt2.close();

            } catch (Exception e) {
                System.out.printf("Error al insertar en la DB: " + e);
            }

        }

    }

    return resp;
}

From source file:com.wsc.myexample.decisionForest.MyTestForest.java

private void testFile(String inPath, String outPath, DataConverter converter, MyDecisionForest forest,
        Dataset dataset, /*List<double[]> results,*/ Random rng, ResultAnalyzer analyzer) throws IOException {
    // create the predictions file
    DataOutputStream ofile = null;

    if (outPath != null) {
        ofile = new DataOutputStream(new FileOutputStream(outPath));
    }//from   w  ww. ja  va  2s .c o  m

    DataInputStream input = new DataInputStream(new FileInputStream(inPath));
    try {
        Scanner scanner = new Scanner(input);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.isEmpty()) {
                continue; // skip empty lines
            }

            Instance instance = converter.convert(line);
            if (instance == null)
                continue;

            double prediction = forest.classify(dataset, rng, instance);

            if (ofile != null) {
                ofile.writeChars(Double.toString(prediction)); // write the prediction
                ofile.writeChar('\n');
            }

            //        results.add(new double[] {dataset.getLabel(instance), prediction});

            analyzer.addInstance(dataset.getLabelString(dataset.getLabel(instance)),
                    new ClassifierResult(dataset.getLabelString(prediction), 1.0));
        }

        scanner.close();
    } finally {
        Closeables.closeQuietly(input);
        ofile.close();
    }
}

From source file:me.prokopyl.commandtools.commands.Commands.java

private void initDescriptions() {
    String fileName = "help/" + getUsualName() + ".txt";
    InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName);
    if (stream == null) {
        PluginLogger.LogWarning("Could not load description file for the " + getUsualName() + " command");
        return;/*  www  . j a  v a  2  s . c  o m*/
    }

    Scanner scanner = new Scanner(stream);
    StringBuilder builder = new StringBuilder();

    //Getting the group's description
    //And then each command's description
    int colonIndex, firstSpaceIndex;
    boolean isGroupDescription = true;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        colonIndex = line.indexOf(':');
        if (isGroupDescription) {
            firstSpaceIndex = line.indexOf(' ');
            if (colonIndex > 0 && firstSpaceIndex > colonIndex)
                isGroupDescription = false;
        }

        if (isGroupDescription) {
            builder.append(line).append('\n');
        } else {
            commandsDescriptions.put(line.substring(0, colonIndex).trim(),
                    line.substring(colonIndex + 1).trim());
        }
    }

    scanner.close();
    description = builder.toString().trim();

}

From source file:com.frankdye.marvelgraphws2.MarvelGraphView.java

private void processLine(String nextLine, Map<String, List<String>> map1, Set<String> set1) {
    // TODO Auto-generated method stub

    // use a second Scanner to parse the content of each line
    Scanner scanner = new Scanner(nextLine);
    scanner.useDelimiter("\t");
    if (scanner.hasNext()) {
        // assumes the line has a certain structure
        String first = scanner.next();
        first = first.replaceAll("^\"|\"$", "");
        String last = scanner.next();
        last = last.replaceAll("^\"|\"$", "");

        // Query map to see if we have an entry for this comic issue
        List<String> l = map1.get(last);
        if (l == null) // No entry for this issue so create it.
        {//from  w w w .  j  a v  a  2s .co  m
            map1.put(last, l = new ArrayList<String>());
        }
        // Issue exists or is created so append the characters name to the
        // map entry for that issue
        l.add(first);
        // Add the characters name to our set to maintain a list of each
        // unique character
        set1.add(first);

    } else {
        log("Empty or invalid line. Unable to process.");
    }
    scanner.close();

}

From source file:languages.TabFile.java

/**
 * Reads the content of the specified *.tab file to this objects variables.
 *
 * @param file The file to read./*from   w w w  . j a  v  a2s . c om*/
 * @throws IOException if the file cannot be read.
 */
private void readFile(URL file) throws IOException {

    // open the file
    Scanner scan = new Scanner(file.openStream(), "UTF-8");

    // get the column headers
    columnHeaders = scan.nextLine().split("   ");

    while (scan.hasNextLine()) {
        ArrayListWithSortableKey<String> temp = new ArrayListWithSortableKey<>(
                Arrays.asList(scan.nextLine().split("   ")));
        while (temp.size() < this.getColumnCount()) {
            // Fill it up
            temp.add("");
        }
        values.add(temp);
    }

    scan.close();
}

From source file:marytts.tools.voiceimport.HMMVoicePackager.java

/**
 * Load mapping of features from file/*  ww w .  java  2 s.c  om*/
 * @param fileName 
 * @throws FileNotFoundException
 */
private Map<String, String> loadFeaturesMap(String fileName) throws FileNotFoundException {

    Scanner aliasList = null;
    try {
        aliasList = new Scanner(new BufferedReader(new FileReader(fileName)));
        String line;
        logger.info("loading features map from file: " + fileName);
        while (aliasList.hasNext()) {
            line = aliasList.nextLine();
            String[] fea = line.split(" ");

            actualFeatureNames.put(fea[1], fea[0]);
            logger.info("  " + fea[0] + " -->  " + fea[1]);
        }
        if (aliasList != null) {
            aliasList.close();
        }
    } catch (FileNotFoundException e) {
        logger.debug("loadTrickyPhones:  " + e.getMessage());
        throw new FileNotFoundException();
    }
    return actualFeatureNames;
}