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:nbayes_mr.NBAYES_MR.java

public static void splitter(String fname) {
    String filePath = new File("").getAbsolutePath();
    Integer count = 0;// w ww  .ja  v a2  s  .  co m
    try {
        Scanner s = new Scanner(new File(fname));
        while (s.hasNext()) {
            count++;
            s.next();
        }
        Integer cnt5 = count / 5;
        System.out.println(count);
        System.out.println(cnt5);
        Scanner sc = new Scanner(new File(fname));
        File file1 = new File("/home/hduser/data1.txt");
        File file2 = new File("/home/hduser/data2.txt");
        File file3 = new File("/home/hduser/data3.txt");
        File file4 = new File("/home/hduser/data4.txt");
        File file5 = new File("/home/hduser/data5.txt");
        file1.createNewFile();
        file2.createNewFile();
        file3.createNewFile();
        file4.createNewFile();
        file5.createNewFile();
        FileWriter fw1 = new FileWriter(file1.getAbsoluteFile());
        BufferedWriter bw1 = new BufferedWriter(fw1);
        FileWriter fw2 = new FileWriter(file2.getAbsoluteFile());
        BufferedWriter bw2 = new BufferedWriter(fw2);
        FileWriter fw3 = new FileWriter(file3.getAbsoluteFile());
        BufferedWriter bw3 = new BufferedWriter(fw3);
        FileWriter fw4 = new FileWriter(file4.getAbsoluteFile());
        BufferedWriter bw4 = new BufferedWriter(fw4);
        FileWriter fw5 = new FileWriter(file5.getAbsoluteFile());
        BufferedWriter bw5 = new BufferedWriter(fw5);
        for (int i = 0; i < cnt5; i++) {
            String l = sc.next();
            bw1.write(l + "\n");
        }
        for (int i = cnt5; i < 2 * cnt5; i++) {
            bw2.write(sc.next() + "\n");

        }
        for (int i = 2 * cnt5; i < 3 * cnt5; i++) {
            bw3.write(sc.next() + "\n");

        }
        for (int i = 3 * cnt5; i < 4 * cnt5; i++) {
            bw4.write(sc.next() + "\n");

        }
        for (int i = 4 * cnt5; i < count; i++) {
            bw5.write(sc.next() + "\n");

        }
        bw1.close();
        bw2.close();
        bw3.close();
        bw4.close();
        bw5.close();
        sc.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnJavaFieldCutter.java

public void subsetFile(InputStream in, String outfile, Set<Integer> columns, Long numCases, String delimiter) {
    try {/*from w w  w .j a v a 2 s.c om*/
        Scanner scanner = new Scanner(in);

        dbgLog.fine("outfile=" + outfile);

        BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
        scanner.useDelimiter("\\n");

        for (long caseIndex = 0; caseIndex < numCases; caseIndex++) {
            if (scanner.hasNext()) {
                String[] line = (scanner.next()).split(delimiter, -1);
                List<String> ln = new ArrayList<String>();
                for (Integer i : columns) {
                    ln.add(line[i]);
                }
                out.write(StringUtils.join(ln, "\t") + "\n");
            } else {
                throw new RuntimeException("Tab file has fewer rows than the determined number of cases.");
            }
        }

        while (scanner.hasNext()) {
            if (!"".equals(scanner.next())) {
                throw new RuntimeException(
                        "Tab file has extra nonempty rows than the determined number of cases.");

            }
        }

        scanner.close();
        out.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.axelor.controller.ConnectionToPrestashop.java

@SuppressWarnings("finally")
@Transactional/*from  ww w .  j  a va2  s  . co  m*/
public String syncCustomerGroup() {
    String message = "";
    try {
        List<Integer> groupIdList = new ArrayList<Integer>();
        List<Integer> erpIdList = new ArrayList<Integer>();
        List<PrestashopCustomerGroup> erpList = PrestashopCustomerGroup.all().fetch();

        for (PrestashopCustomerGroup prestahopCustomerGroup : erpList) {
            erpIdList.add(prestahopCustomerGroup.getId_group());
        }

        URL url = new URL(
                "http://localhost/client-lib/crud/action.php?resource=groups&action=getallid&Akey=" + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        InputStream inputStream = connection.getInputStream();
        Scanner scan = new Scanner(inputStream);
        while (scan.hasNext()) {
            String data = scan.nextLine();
            System.out.println(data);
            groupIdList.add(Integer.parseInt(data));
        }
        System.out.println("From Prestashop :: " + groupIdList.size());
        System.out.println("From ERP :: " + erpIdList.size());
        scan.close();

        // Check new entries in the prestahop
        Iterator<Integer> prestaListIterator = groupIdList.iterator();
        while (prestaListIterator.hasNext()) {
            Integer tempId = prestaListIterator.next();
            System.out.println("Current prestaid for operation ::" + tempId);
            if (erpIdList.contains(tempId)) {
                erpIdList.remove(tempId);
            } else {
                System.out.println("Current prestaid for insertion operation ::" + tempId);
                // insert new data in ERP Database
                insertGroup(tempId);
                erpIdList.remove(tempId);
            }
        }
        if (erpIdList.isEmpty()) {
            System.out.println("Synchronization is completed.");
            message = "done";
        } else {
            // delete from ERP
            Iterator<Integer> erpListIterator = erpIdList.iterator();
            while (erpListIterator.hasNext()) {
                Integer tempId = erpListIterator.next();
                System.out.println("Currently in  Erp ::" + tempId);
                if (tempId != 0) {
                    PrestashopCustomerGroup customerGroupDelete = PrestashopCustomerGroup.all()
                            .filter("id_group=?", tempId).fetchOne();
                    String groupName = customerGroupDelete.getName();
                    // customerGroupDelete.remove();
                    customerGroupDelete.setArchived(Boolean.TRUE);
                    System.out.println("customer deleted ::" + groupName);
                }
            }
            while (prestaListIterator.hasNext()) {
                Integer tempId = prestaListIterator.next();
                System.out.println("Currently in prestashop ::" + tempId);
            }
            System.out.println("Synchronization is completed.");
            message = "done";
        }
    } catch (Exception e) {
        message = "Wrong Authentication Key or Key has been disabled.";
    } finally {
        return message;
    }
}

From source file:fr.zcraft.zlib.components.commands.CommandGroup.java

private void initDescriptions() {
    String fileName = "help/" + getUsualName() + ".txt";
    InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName);
    if (stream == null) {
        PluginLogger.warning("Could not load description file for the " + getUsualName() + " command");
        return;/*from w  w  w. j a v a2s . c om*/
    }

    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.axelor.controller.ConnectionToPrestashop.java

@SuppressWarnings("finally")
@Transactional/*from w w w.ja v  a  2  s  .co m*/
public String syncCurrency() {
    String message = "";
    try {
        List<Integer> currencyIdList = new ArrayList<Integer>();
        List<Integer> erpIdList = new ArrayList<Integer>();
        List<Currency> erpList = Currency.all().fetch();

        for (Currency erpCurrency : erpList) {
            erpIdList.add(erpCurrency.getPrestashopCurrencyId());
        }

        URL url = new URL(
                "http://localhost/client-lib/crud/action.php?resource=currencies&action=getallid&Akey="
                        + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        InputStream inputStream = connection.getInputStream();
        Scanner scan = new Scanner(inputStream);
        while (scan.hasNext()) {
            String data = scan.nextLine();
            System.out.println(data);
            currencyIdList.add(Integer.parseInt(data));
        }
        System.out.println("From Prestashop :: " + currencyIdList.size());
        System.out.println("From ERP :: " + erpIdList.size());
        scan.close();

        // Check new entries in the prestahop
        Iterator<Integer> prestaListIterator = currencyIdList.iterator();
        while (prestaListIterator.hasNext()) {
            Integer tempId = prestaListIterator.next();
            System.out.println("Current prestaid for operation ::" + tempId);
            if (erpIdList.contains(tempId)) {
                erpIdList.remove(tempId);
            } else {
                System.out.println("Current prestaid for insertion operation ::" + tempId);
                // insert new data in ERP Database
                insertCurrency(tempId);
                erpIdList.remove(tempId);
            }
        }
        if (erpIdList.isEmpty()) {
            System.out.println("Synchronization is completed.");
            message = "done";
        } else {
            // delete from ERP
            Iterator<Integer> erpListIterator = erpIdList.iterator();
            while (erpListIterator.hasNext()) {
                Integer tempId = erpListIterator.next();
                if (tempId != 0) {
                    System.out.println("Currently in  Erp ::" + tempId);
                    Currency currencyDelete = Currency.all().filter("prestashopCurrencyId=?", tempId)
                            .fetchOne();
                    String currencyName = currencyDelete.getName();
                    // customerGroupDelete.remove();
                    currencyDelete.setArchived(Boolean.TRUE);
                    System.out.println("customer deleted ::" + currencyName);
                }
            }
            while (prestaListIterator.hasNext()) {
                Integer tempId = prestaListIterator.next();
                System.out.println("Currently in prestashop ::" + tempId);
            }
            System.out.println("Synchronization is completed.");
            message = "done";
        }
    } catch (Exception e) {
        message = "Wrong Authentication Key or Key has been disabled.";
    } finally {
        return message;
    }
}

From source file:edu.cmu.lti.oaqa.framework.eval.gs.PassageGoldStandardFilePersistenceProvider.java

@Override
public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams)
        throws ResourceInitializationException {
    boolean ret = super.initialize(aSpecifier, aAdditionalParams);
    String dataset = (String) getParameterValue("DataSet");
    Pattern lineSyntaxPattern = Pattern.compile((String) getParameterValue("LineSyntax"));
    try {/* ww  w  . j  av  a2 s.  c  o m*/
        Resource[] resources = resolver.getResources((String) getParameterValue("PathPattern"));
        for (Resource resource : resources) {
            Scanner scanner = new Scanner(resource.getInputStream());
            while (scanner.findInLine(lineSyntaxPattern) != null) {
                MatchResult result = scanner.match();
                DatasetSequenceId id = new DatasetSequenceId(dataset, result.group(1));
                List<GoldStandardSpan> list = id2gsSpans.get(id);
                if (list == null) {
                    list = new ArrayList<GoldStandardSpan>();
                    id2gsSpans.put(id, list);
                }
                GoldStandardSpan annotation = new GoldStandardSpan(result.group(2),
                        Integer.parseInt(result.group(3)), Integer.parseInt(result.group(4)), result.group(5));
                list.add(annotation);
                if (scanner.hasNextLine()) {
                    scanner.nextLine();
                } else {
                    break;
                }
            }
            scanner.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:com.axelor.controller.ConnectionToPrestashop.java

@Transactional
@SuppressWarnings("finally")
public String syncCustomer() {
    String message = "";
    try {/*from   w  w  w  .j  a  v a2s . co m*/
        List<Integer> prestashopIdList = new ArrayList<Integer>();
        List<Integer> erpIdList = new ArrayList<Integer>();
        List<Partner> erpList = Partner.all().fetch();

        for (Partner prestahopCustomer : erpList) {
            erpIdList.add(prestahopCustomer.getPrestashopid());
        }
        System.out.println("API KEY :: " + apiKey);
        URL url = new URL("http://localhost/client-lib/crud/action.php?resource=customers&action=getallid&Akey="
                + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        InputStream inputStream = connection.getInputStream();
        Scanner scan = new Scanner(inputStream);
        while (scan.hasNext()) {
            String data = scan.nextLine();
            System.out.println(data);
            prestashopIdList.add(Integer.parseInt(data));
        }
        System.out.println("From Prestashop :: " + prestashopIdList.size());
        System.out.println("From ERP :: " + erpIdList.size());
        scan.close();

        // Check new entries in the prestshop
        Iterator<Integer> prestaListIterator = prestashopIdList.iterator();
        while (prestaListIterator.hasNext()) {
            Integer tempId = prestaListIterator.next();
            System.out.println("Current prestaid for operation ::" + tempId);
            if (erpIdList.contains(tempId)) {
                Customer tempCustomer = getCustomer(tempId);
                String dateUpdate = tempCustomer.getDate_upd();
                LocalDateTime dt1 = LocalDateTime.parse(dateUpdate,
                        DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
                Partner pCust = Partner.all().filter("prestashopId=?", tempId).fetchOne();
                LocalDateTime dt2 = pCust.getUpdatedOn();
                if (dt2 != null) {
                    int diff = Seconds.secondsBetween(dt2, dt1).getSeconds();
                    if (diff > 1)
                        updateCustomer(tempCustomer, tempId);
                } else {
                    updateCustomer(tempCustomer, tempId);
                }
                erpIdList.remove(tempId);
            } else {
                System.out.println("Current prestaid for insertion operation ::" + tempId);
                // insert new data in ERP Database
                insertCustomer(tempId);
                erpIdList.remove(tempId);
            }
        }
        if (erpIdList.isEmpty()) {
            System.out.println("Synchronization is completed.");
            message = "done";
        } else {
            // delete from ERP
            Iterator<Integer> erpListIterator = erpIdList.iterator();
            while (erpListIterator.hasNext()) {
                Integer tempId = erpListIterator.next();
                if (tempId != 0) {
                    System.out.println("Currently in  Erp ::" + tempId);
                    Partner customerDelete = Partner.all().filter("prestashopid=?", tempId).fetchOne();
                    String firstName = customerDelete.getFirstName();
                    customerDelete.setArchived(Boolean.TRUE);
                    System.out.println("customer deleted ::" + firstName);
                }
            }
            while (prestaListIterator.hasNext()) {
                Integer tempId = prestaListIterator.next();
                System.out.println("Currently in prestashop ::" + tempId);
            }
            System.out.println("Synchronization is completed.");
            message = "done";
        }
    } catch (Exception e) {
        message = "Wrong Authentication Key or Key has been disabled.";
    } finally {
        return message;
    }
}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

private void processScriptFile(final DB db, final File scriptFile) throws MojoExecutionException {
    Scanner scanner = null;
    final StringBuilder instructions = new StringBuilder();
    try {//from  w w w  .  j ava 2s  . c  o  m
        scanner = new Scanner(scriptFile);
        while (scanner.hasNextLine()) {
            instructions.append(scanner.nextLine()).append("\n");
        }
    } catch (final FileNotFoundException e) {
        throw new MojoExecutionException("Unable to find file with name '" + scriptFile.getName() + "'", e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    final CommandResult result;
    try {
        final String evalString = "(function() {" + instructions.toString() + "})();";
        result = db.doEval(evalString, new Object[0]);
    } catch (final MongoException e) {
        throw new MojoExecutionException("Unable to execute file with name '" + scriptFile.getName() + "'", e);
    }
    if (!result.ok()) {
        getLog().error("- file " + scriptFile.getName() + " parsed with error: " + result.getErrorMessage());
        throw new MojoExecutionException("Error while executing instructions from file '" + scriptFile.getName()
                + "': " + result.getErrorMessage(), result.getException());
    }
    getLog().info("- file " + scriptFile.getName() + " parsed successfully");
}

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

/**
 * Initializes the conversion map with some predefined
 * files. Each file contains a list of FB types associated
 * (mainly) to a specific type. An additional file contains
 * a list of ignored types (for debugging purposes, and to
 * ease the future completion of these files).
 * //  w  ww.j  a  v  a  2  s .  c o  m
 * @throws FileNotFoundException
 *       Problem while accessing one of the map files.
 */
private synchronized void loadTypeMaps() throws FileNotFoundException {
    if (TYPE_MAP.isEmpty()) {
        logger.log("Loading type maps");
        logger.increaseOffset();

        // set up the list of types
        String base = FileNames.FO_SUBEE + File.separator;
        List<EntityType> types = new ArrayList<EntityType>(HANDLED_TYPES);
        types.add(null); // for the ignored types

        // process each corresponding file
        for (EntityType type : types) { // open file
            String name = FILE_IGNORED;
            if (type != null)
                name = type.toString().toLowerCase();
            String filePath = base + FILE_PREFIX + name + FileNames.EX_TXT;
            logger.log("Processing file " + filePath);
            Scanner scanner = FileTools.openTextFileRead(filePath);

            // read the content and add to the conversion map
            while (scanner.hasNextLine()) {
                String string = scanner.nextLine().trim();
                TYPE_MAP.put(string, type);
            }

            scanner.close();
        }

        logger.decreaseOffset();
        logger.log("Type maps loading complete");
    }
}

From source file:com.joliciel.csvLearner.EventCombinationGenerator.java

void scanResultsFile() {
    Scanner resultScanner;
    try {/*from ww  w  .  j  av a 2 s. c o  m*/
        resultScanner = new Scanner(new FileInputStream(resultFilePath), "UTF-8");

        try {
            boolean firstLine = true;
            while (resultScanner.hasNextLine()) {
                String line = resultScanner.nextLine();
                if (!firstLine) {
                    List<String> cells = CSVFormatter.getCSVCells(line);
                    String ref = cells.get(0);
                    String outcome = cells.get(1);
                    List<String> eventsForThisOutcome = this.eventsPerOutcome.get(outcome);
                    if (eventsForThisOutcome == null) {
                        eventsForThisOutcome = new ArrayList<String>();
                        this.eventsPerOutcome.put(outcome, eventsForThisOutcome);
                    }
                    eventsForThisOutcome.add(ref);
                }
                firstLine = false;

            }
        } finally {
            resultScanner.close();
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}