Example usage for java.util Scanner nextLine

List of usage examples for java.util Scanner nextLine

Introduction

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

Prototype

public String nextLine() 

Source Link

Document

Advances this scanner past the current line and returns the input that was skipped.

Usage

From source file:mase.evorbc.KdTreeRepertoire.java

private Map<Integer, double[]> fileCoordinates(File file) {
    Map<Integer, double[]> res = new HashMap<>();
    try {//from  w ww. j  a  v a 2  s. c  om
        Scanner sc = new Scanner(file);
        while (sc.hasNext()) {
            String line = sc.nextLine();
            String[] split = line.trim().split(" ");
            int index = Integer.parseInt(split[0]);
            double[] coords = new double[split.length - 1];
            for (int i = 0; i < coords.length; i++) {
                coords[i] = Double.parseDouble(split[i + 1]);
            }
            res.put(index, coords);
        }
        return res;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ArbitratorFactory.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:org.apache.streams.datasift.serializer.DatasiftInteractionActivitySerializerTest.java

@Test
@Override//  w  ww.j  a  v a 2  s . c om
public void testConversion() throws Exception {

    Scanner scanner = StreamsScannerUtil.getInstance("/rand_sample_datasift_json.txt");

    String line = null;
    while (scanner.hasNextLine()) {
        try {
            line = scanner.nextLine();
            Datasift item = MAPPER.readValue(line, Datasift.class);
            testConversion(item);
            String json = MAPPER.writeValueAsString(item);
            testDeserNoNull(json);
            testDeserNoAddProps(json);
        } catch (Exception e) {
            System.err.println(line);
            throw e;
        }
    }
}

From source file:io.github.binout.wordpress2html.writer.PostWriter.java

private String getFullHtml() {

    String content = post.getHtmlContent();
    boolean pre = false;
    StringBuilder builder = new StringBuilder();

    Scanner scanner = new Scanner(content);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        // String line;
        // process the line
        line = line.replaceAll("</?pre>", " ");
        if (line.contains("[code") || line.contains("[sourcecode")) {
            pre = true;/*from   w w w.j a va2  s . c o  m*/
        }

        if (pre) {
            if (line.contains("[/code") || line.contains("[/sourcecode")) {
                pre = false;
            }
            line = line.replaceAll("<", "&lt;");
            line = line.replaceAll(">", "&gt;");
            line = line.replaceAll("&", "&amp;");
            line = line.replaceAll("(\\[.*code .*\\])", "$1<pre>");
            line = line.replaceAll("(\\[\\/.*code\\])", "</pre>");
            builder.append(line).append("\n");

        } else {
            builder.append(line).append("</p><p>");

        }

    }
    scanner.close();

    if (post.getTitle().startsWith("XML")) {
        System.out.println(builder.toString());
    }

    return "<html><head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
            + "</head>" + "<body>" + builder.toString() + "</body></html>";
}

From source file:com.neu.bigdata.service.PredictionService.java

public String setJSON(String fileName) {

    try {/*from   w w w .j a  va  2  s .  c om*/

        File apiFile = new File(fileName);
        Scanner sc = new Scanner(apiFile);
        while (sc.hasNext()) {
            jsonBody += sc.nextLine() + "\n";
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        return jsonBody;
    }

}

From source file:org.sasabus.export2Freegis.network.DataRequestManager.java

public String datarequest() throws IOException {
    Scanner sc = new Scanner(new File(DATAREQUEST));
    String subscriptionstring = "";
    while (sc.hasNextLine()) {
        subscriptionstring += sc.nextLine();
    }/*  w w  w. j  a va  2s  .c  om*/
    sc.close();
    SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

    Date d = new Date();
    String timestamp = date_date.format(d) + "T" + date_time.format(d);
    timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
            + timestamp.substring(timestamp.length() - 2);

    subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp);

    String requestString = "http://" + this.address + ":" + this.portnumber_sender
            + "/TmEvNotificationService/gms/polldata.xml";

    HttpPost subrequest = new HttpPost(requestString);

    StringEntity requestEntity = new StringEntity(subscriptionstring,
            ContentType.create("text/xml", "ISO-8859-1"));

    CloseableHttpClient httpClient = HttpClients.createDefault();

    subrequest.setEntity(requestEntity);

    CloseableHttpResponse response = httpClient.execute(subrequest);
    //System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode());
    //System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase());
    HttpEntity responseEntity = response.getEntity();
    String responsebody = "";
    if (responseEntity != null) {
        responsebody = EntityUtils.toString(responseEntity);
    }
    return responsebody;
}

From source file:view.UserInteractor.java

private void userInputCycle(Scanner in) {
    String input;//from w  ww. j  a  va  2s  .  com
    System.out.println("Enter payment ([CURRENCY] [amount]) or \"quit\" to exit: ");
    while (true) {
        input = in.nextLine();

        if (input.equals("q"))
            break;
        if (input.equals("quit"))
            break;

        try {
            Money payment = new Money(input);
            controller.paymentEntered(payment);
        } catch (InputMismatchException exc) {
            System.out.println("Invalid format. [A-Z][A-Z][A-Z] [n]   e.g. USD -500");
        }
    }
}

From source file:ZipTest.java

/**
 * Loads a file from the ZIP archive into the text area
 * @param name the name of the file in the archive
 *//* ww  w . j a v  a2  s .  c  o m*/
public void loadZipFile(final String name) {
    fileCombo.setEnabled(false);
    fileText.setText("");
    new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {
            try {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
                ZipEntry entry;

                // find entry with matching name in archive
                while ((entry = zin.getNextEntry()) != null) {
                    if (entry.getName().equals(name)) {
                        // read entry into text area
                        Scanner in = new Scanner(zin);
                        while (in.hasNextLine()) {
                            fileText.append(in.nextLine());
                            fileText.append("\n");
                        }
                    }
                    zin.closeEntry();
                }
                zin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void done() {
            fileCombo.setEnabled(true);
        }
    }.execute();
}

From source file:com.btobits.automator.fix.utils.FileMessageFactory.java

public void load() throws Exception {
    try {/*from  www .j ava2  s  .  c  om*/
        Scanner scanner = new Scanner(new FileInputStream(file));

        while (scanner.hasNextLine()) {
            final String line = scanner.nextLine();

            if (StringUtils.isBlank(line)) {
                continue;
            }

            int i = line.indexOf("8=FIX");
            if (i != -1) {
                String s = line.substring(i);
                final String type = MessageUtils.getStringField(s, FixUtils.MSGTYPE);
                if (!isSkip(type)) {
                    messages.add(s);
                }
            }
        }
    } catch (Exception ex) {
        throw new Exception("Error load from file", ex);
    }
}

From source file:net.bashtech.geobot.BotManager.java

public static String postRemoteDataSongRequest(String urlString, String channel, String requester) {
    if (BotManager.getInstance().CoeBotTVAPIKey.length() > 4) {
        URL url;//from  w w  w. j  a  va 2s .  co m
        HttpURLConnection conn;

        try {
            url = new URL("http://coebot.tv/api/v1/reqsongs/add/" + channel.toLowerCase() + "$"
                    + BotManager.getInstance().CoeBotTVAPIKey + "$" + BotManager.getInstance().nick);

            String postData = "url=" + URLEncoder.encode(urlString, "UTF-8") + "&requestedBy="
                    + URLEncoder.encode(requester, "UTF-8");
            conn = (HttpURLConnection) url.openConnection();
            System.out.println(postData);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent", "CoeBot");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));

            // conn.setConnectTimeout(5 * 1000);
            // conn.setReadTimeout(5 * 1000);

            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(postData);
            out.close();
            String response = "";
            if (conn.getResponseCode() < 400) {

                Scanner inStream = new Scanner(conn.getInputStream());

                while (inStream.hasNextLine()) {
                    response += (inStream.nextLine());
                }
                inStream.close();
            } else {
                Scanner inStream = new Scanner(conn.getErrorStream());

                while (inStream.hasNextLine()) {
                    response += (inStream.nextLine());
                }
                inStream.close();
            }
            System.out.println(response);

            return response;

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();

        }

        return null;
    } else {
        return null;
    }

}

From source file:com.hortonworks.registries.storage.tool.shell.ShellMigrationExecutor.java

@Override
public void execute(Connection connection) throws SQLException {
    String scriptLocation = this.shellScriptResource.getLocationOnDisk();
    try {/*from w  w w . ja  v  a2 s.  co m*/
        List<String> args = new ArrayList<String>();
        args.add(scriptLocation);
        ProcessBuilder builder = new ProcessBuilder(args);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        Scanner in = new Scanner(process.getInputStream());
        System.out.println(StringUtils.repeat("+", 200));
        while (in.hasNextLine()) {
            System.out.println(in.nextLine());
        }
        int returnCode = process.waitFor();
        System.out.println(StringUtils.repeat("+", 200));
        if (returnCode != 0) {
            throw new FlywayException("script exited with value : " + returnCode);
        }
    } catch (Exception e) {
        LOG.error(e.toString());
        // Only if SQLException or FlywaySqlScriptException is thrown flyway will mark the migration as failed in the metadata table
        throw new SQLException(String.format("Failed to run script \"%s\", %s", scriptLocation, e.getMessage()),
                e);
    }
}