Example usage for java.util Scanner hasNext

List of usage examples for java.util Scanner hasNext

Introduction

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

Prototype

public boolean hasNext() 

Source Link

Document

Returns true if this scanner has another token in its input.

Usage

From source file:GUI.MyCustomFilter.java

private void OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenActionPerformed
    if (projectSelected == 1) {
        JFileChooser chooser = new JFileChooser();
        int chooserValue = chooser.showOpenDialog(this);
        if (chooserValue == JFileChooser.APPROVE_OPTION) {
            String path = chooser.getSelectedFile().getAbsolutePath();
            String ext = FilenameUtils.getExtension(path);

            if (ext.equalsIgnoreCase("cpp")) {
                try {
                    fileSelected = 1;/*  w  w w . ja v a 2 s.  com*/
                    Scanner fin = new Scanner(chooser.getSelectedFile());
                    String buffer = "";
                    while (fin.hasNext()) {
                        buffer += fin.nextLine() + "\n";
                    }
                    textarea.setText(buffer);
                    miniFile = path;
                    jTextPane2.setText(path);
                    //startButton.setVisible(true);
                } catch (FileNotFoundException ex) {
                    //Logger.getLogger(TextEditorFrame.class.getName()).log(Level.SEVERE, null, ex);   
                }

            } else {
                JOptionPane.showMessageDialog(this, "Please input .cpp or .c extension file",
                        "File Inaccessable", JOptionPane.ERROR_MESSAGE);
            }

        }
    } else {
        JOptionPane.showMessageDialog(this, "Select New Project first", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:GUI.MyCustomFilter.java

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
    if (projectSelected == 1) {
        JFileChooser chooser = new JFileChooser();
        int chooserValue = chooser.showOpenDialog(this);
        if (chooserValue == JFileChooser.APPROVE_OPTION) {
            String path = chooser.getSelectedFile().getAbsolutePath();
            String ext = FilenameUtils.getExtension(path);

            if (ext.equalsIgnoreCase("cpp")) {
                try {
                    fileSelected = 1;/* ww  w  .j  a  v a2 s  . co  m*/
                    Scanner fin = new Scanner(chooser.getSelectedFile());
                    String buffer = "";
                    while (fin.hasNext()) {
                        buffer += fin.nextLine() + "\n";
                    }
                    textarea.setText(buffer);
                    miniFile = path;
                    jTextPane2.setText(path);
                    //startButton.setVisible(true);
                } catch (FileNotFoundException ex) {
                    //Logger.getLogger(TextEditorFrame.class.getName()).log(Level.SEVERE, null, ex);   
                }

            } else {
                JOptionPane.showMessageDialog(this, "Please input .cpp or .c extension file",
                        "File Inaccessable", JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane.showMessageDialog(this, "Select New Project first", "Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:com.klarna.checkout.stubs.HttpClientStub.java

/**
 * Uppercase data to simulate it having passed on to the server.
 *
 * @throws IOException in case of an IO error.
 *//*from  w w  w . j a  va2s . c o  m*/
private void fixData() throws IOException {
    if (this.httpUriReq.getMethod().equals("POST")) {
        HttpEntityEnclosingRequest h = (HttpEntityEnclosingRequest) this.httpUriReq;

        InputStream is = h.getEntity().getContent();
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");

        String str = "";
        while (s.hasNext()) {
            str = str.concat(s.next());
        }
        JSONParser jsonParser = new JSONParser();
        HashMap<String, String> obj = null;
        try {
            obj = (HashMap<String, String>) jsonParser.parse(str);
        } catch (ParseException ex) {
            Logger.getLogger(HttpClientStub.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (obj != null && obj.containsKey("test")) {
            str = obj.get("test").toUpperCase();
            this.data.put("test", str);
        }

        ByteArrayInputStream in = new ByteArrayInputStream(JSONObject.toJSONString(this.data).getBytes());

        this.lastResponse.setEntity(new InputStreamEntity(in, in.available()));
    }
}

From source file:eremeykin.pete.plotter.CartesianPlotterTopComponent.java

@Override
public void update() {
    // for first rpt file
    if (model == null) {
        clear();//from   w w w  . j  ava 2 s.co  m
        return;
    }
    File[] rptFiles = home.listFiles(filter());
    // catch if there is no such file
    if (rptFiles.length == 0) {
        clear();
        return;
    }
    File firstRPT = rptFiles[0];

    Scanner scanner;
    try {
        scanner = new Scanner(firstRPT);
        scanner.useDelimiter("\\s+|\n");
    } catch (FileNotFoundException ex) {
        clear();
        return;
    }
    List<Map.Entry<Double, Double>> tmpList = new ArrayList<>();
    for (int i = 0; scanner.hasNext(); i++) {
        String line = scanner.next();
        try {
            double x1 = Double.valueOf(line);
            line = scanner.next();
            double x2 = Double.valueOf(line);
            //                System.out.println("x1=" + x1 + "\nx2=" + x2);
            tmpList.add(new AbstractMap.SimpleEntry<>(x1, x2));
        } catch (NumberFormatException ex) {
            // only if it is the third or following line
            if (i > 1) {
                LOGGER.error("Error while parsing double from file: " + firstRPT.getAbsolutePath());
                JOptionPane.showMessageDialog(this, "Error while parsing result file.", "Parsing error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }

    }
    if (tmpList.isEmpty()) {
        clear();
        return;
    }
    fillData(tmpList);

}

From source file:in.rab.ordboken.NeClient.java

private String inputStreamToString(InputStream input) throws IOException {
    Scanner scanner = new Scanner(input).useDelimiter("\\A");
    String str = scanner.hasNext() ? scanner.next() : "";

    input.close();//from  w  w  w  .j a v  a  2  s  . co m

    return str;
}

From source file:com.zilotti.hostsjuggler.view.ActiveHostsFileWindow.java

/**
 * Parses a hosts file and loads it into its corresponding Javabean 
 * representation./* w ww. j  av a  2s  . c om*/
 *  
 * @param hostsFile
 * @return
 * @throws IOException
 */
private HostsFile loadHostsFile(File hostsFile) throws IOException, ParseException {
    /* Object to be returned */
    HostsFile hostsFileObject = new HostsFile();

    BufferedReader br = null;

    int lineCounter = 1;
    try {
        br = new BufferedReader(new FileReader(hostsFile));

        String line = null;
        while ((line = br.readLine()) != null) {
            line += "\n";

            /* Remark */
            if (line.startsWith(REM_LINE_CHAR)) {
                CommentLine commentLine = new CommentLine();
                commentLine.setLine(line);
                hostsFileObject.addLine(commentLine);
            } else if (StringUtils.isBlank(line)) // Blank line
            {
                BlankLine blankLine = new BlankLine();
                blankLine.setLine(line);
                hostsFileObject.addLine(blankLine);
            } else {
                Scanner scanner = new Scanner(line);
                HostLine hostLine = new HostLine();

                if (scanner.hasNext()) {
                    /* Expects an IP address */
                    String ipAddress = scanner.next();

                    if (NetworkUtils.isIpAddress(ipAddress)) {
                        hostLine.setIpAddress(ipAddress);
                    } else
                        throw new ParseException("Expected an IP address but found '" + ipAddress + "'",
                                lineCounter);

                    /* Expects a list of hostnames */
                    List<String> hostNames = new LinkedList<String>();
                    String hostName = null;
                    while (scanner.hasNext()) {
                        hostName = scanner.next();

                        if (NetworkUtils.isHostName(hostName)) {
                            hostNames.add(hostName);
                        } else
                            throw new ParseException("Expected a hostname but found '" + hostName + "'",
                                    lineCounter);
                    }

                    hostLine.setHostNames(hostNames);
                    hostLine.setLine(line);
                    hostsFileObject.addLine(hostLine);
                }
            }
        }
    } finally {
        if (br != null)
            br.close();
    }

    return hostsFileObject;
}

From source file:ml.shifu.shifu.core.processor.InitModelProcessor.java

private Map<Integer, Data> getCountInfoMap(SourceType source, String autoTypePath) throws IOException {
    String outputFilePattern = autoTypePath + Path.SEPARATOR + "part-*";
    if (!ShifuFileUtils.isFileExists(outputFilePattern, source)) {
        throw new RuntimeException("Auto type checking output file not exist.");
    }// w  w w  .  ja v  a  2 s  .c om

    Map<Integer, Data> distinctCountMap = new HashMap<Integer, Data>();
    List<Scanner> scanners = null;
    try {
        // here only works for 1 reducer
        FileStatus[] globStatus = ShifuFileUtils.getFileSystemBySourceType(source)
                .globStatus(new Path(outputFilePattern));
        if (globStatus == null || globStatus.length == 0) {
            throw new RuntimeException("Auto type checking output file not exist.");
        }
        scanners = ShifuFileUtils.getDataScanners(globStatus[0].getPath().toString(), source);
        Scanner scanner = scanners.get(0);
        String str = null;
        while (scanner.hasNext()) {
            str = scanner.nextLine().trim();
            if (str.contains(TAB_STR)) {
                String[] splits1 = str.split(TAB_STR);
                String[] splits2 = splits1[1].split(":", -1);

                distinctCountMap.put(Integer.valueOf(splits1[0]),
                        new Data(Long.valueOf(splits2[0]), Long.valueOf(splits2[1]), Long.valueOf(splits2[2]),
                                Long.valueOf(splits2[3]), splits2[4].split(",")));
            }
        }
        return distinctCountMap;
    } finally {
        if (scanners != null) {
            for (Scanner scanner : scanners) {
                if (scanner != null) {
                    scanner.close();
                }
            }
        }
    }
}

From source file:files.populate.java

private void populate_reviews(Connection connection, String string) {

    String fileName = "/Users/yash/Documents/workspace/HW 3/data/yelp_review.json";
    Path path = Paths.get(fileName);
    Scanner scanner = null;
    try {//from  ww  w. ja  va  2s.c  o  m
        scanner = new Scanner(path);

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

    //read file line by line
    scanner.useDelimiter("\n");
    int i = 0;
    while (scanner.hasNext()) {
        if (i < 20) {
            JSONParser parser = new JSONParser();
            String s = (String) scanner.next();
            s = s.replace("'", "''");

            JSONObject obj;

            try {
                obj = (JSONObject) parser.parse(s);
                String text = (String) obj.get("text");
                text = text.replace("\n", "");

                Map votes = (Map) obj.get("votes");
                String query = "insert into yelp_reviews values (" + votes.get("useful") + ","
                        + votes.get("funny") + "," + votes.get("cool") + ",'" + obj.get("user_id") + "','"
                        + obj.get("review_id") + "'," + obj.get("stars") + ",'" + obj.get("date") + "','" + text
                        + "','" + obj.get("type") + "','" + obj.get("business_id") + "')";
                System.out.println(query);
                Statement statement = connection.createStatement();
                statement.executeUpdate(query);
                statement.close();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ++i;

        }

    }
}

From source file:eu.cassandra.training.entities.Appliance.java

/**
 * This function is the parser of the consumption model provided by the user.
 * //w w  w.  j a v  a 2  s  . c  om
 * @param filename
 *          The file name of the consumption model
 * @throws IOException
 */
public void parseConsumptionModel(String filename) throws IOException {

    File file = new File(filename);

    String model = "";

    String extension = filename.substring(filename.length() - 3, filename.length());

    Scanner scanner = new Scanner(file);
    switch (extension) {

    case "son":

        while (scanner.hasNext())
            model = model + scanner.nextLine();
        break;
    default:

        while (scanner.hasNext())
            model = model + scanner.nextLine();

        model.replace(" ", "");
    }
    scanner.close();

    activeConsumptionModelString = model;
    DBObject dbo = (DBObject) JSON.parse(activeConsumptionModelString);
    activeConsumptionModel.init(dbo);

    reactiveConsumptionModelString = activeConsumptionModelString.replace("p", "q");
    reactiveConsumptionModelString = reactiveConsumptionModelString.replace("qara", "para");
    System.out.println(reactiveConsumptionModelString);
    dbo = (DBObject) JSON.parse(reactiveConsumptionModelString);
    reactiveConsumptionModel.init(dbo);

}

From source file:files.populate.java

private void populate_checkin(Connection connection, String string) {
    String fileName = "/Users/yash/Documents/workspace/HW 3/data/yelp_checkin.json";
    Path path = Paths.get(fileName);
    Scanner scanner = null;
    try {/*from w  w  w .  java2s  .  c om*/
        scanner = new Scanner(path);

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

    //read file line by line
    scanner.useDelimiter("\n");
    int i = 0;
    while (scanner.hasNext()) {

        if (i < 20) {
            JSONParser parser = new JSONParser();
            String s = (String) scanner.next();
            s = s.replace("'", "''");

            JSONObject obj;

            try {
                obj = (JSONObject) parser.parse(s);
                Map checkin_info = (Map) obj.get("checkin_info");
                Set keys = checkin_info.keySet();
                Object[] days = keys.toArray();
                Statement statement = connection.createStatement();
                for (int j = 0; j < days.length; ++j) {
                    //                           
                    String thiskey = days[j].toString();
                    String q3 = "insert into yelp_checkin values ('" + obj.get("business_id") + "','"
                            + obj.get("type") + "','" + thiskey + "','" + checkin_info.get(thiskey) + "')";
                    //
                    statement.executeUpdate(q3);

                }
                statement.close();

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            ++i;
        } else {
            break;
        }
    }
}