Example usage for java.util Scanner Scanner

List of usage examples for java.util Scanner Scanner

Introduction

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

Prototype

public Scanner(ReadableByteChannel source) 

Source Link

Document

Constructs a new Scanner that produces values scanned from the specified channel.

Usage

From source file:SystemTrayTest.java

private static List<String> readFortunes() {
    List<String> fortunes = new ArrayList<String>();
    try {/*w w  w .ja v a 2 s  .com*/
        Scanner in = new Scanner(new File("fortunes"));
        StringBuilder fortune = new StringBuilder();
        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (line.equals("%")) {
                fortunes.add(fortune.toString());
                fortune = new StringBuilder();
            } else {
                fortune.append(line);
                fortune.append(' ');
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return fortunes;
}

From source file:hu.sztaki.incremental.ml.streaming.imsr.MatrixVectorPairSource.java

@Override
public void invoke(Collector<Tuple2<double[][], double[][]>> out) throws Exception {
    File f = new File(path);
    if (!f.exists()) {
        System.err.println(path + " does not exist.");
        System.exit(1);//from  w  w w. ja va  2  s . co m
    }
    Scanner s = initCsvScanner(new Scanner(f));
    String firstLine = s.nextLine();
    Scanner firstLineScanner = initCsvScanner(new Scanner(firstLine));
    for (indepDim = 0; firstLineScanner.hasNext(); firstLineScanner.next(), indepDim++)
        ;
    indepDim--;
    while (s.hasNext()) {
        Array2DRowRealMatrix X = new Array2DRowRealMatrix(batchSize, indepDim);
        Array2DRowRealMatrix y = new Array2DRowRealMatrix(batchSize, 1);
        readMatricesSideBySide(s, X, y);
        out.collect(new Tuple2<double[][], double[][]>(X.getDataRef(), y.getDataRef()));
    }
    s.close();
    out.close();
}

From source file:com.freemedforms.openreact.db.DbSchema.java

/**
 * Attempt to run a database patch.//  w w  w . ja v a2  s .  co  m
 * 
 * @param patchFilename
 * @return Success.
 * @throws SQLException
 */
public static boolean applyPatch(String patchFilename) throws SQLException {
    Connection c = Configuration.getConnection();

    String patch = null;

    Scanner scanner;
    try {
        scanner = new Scanner(new File(patchFilename)).useDelimiter("\\Z");
        patch = scanner.next();
        scanner.close();
    } catch (FileNotFoundException ex) {
        log.error(ex);
        return false;
    }

    Statement cStmt = c.createStatement();
    boolean status = false;
    try {
        log.debug("Using patch length = " + patch.length());
        cStmt.execute(patch);
        // cStmt = c.prepareStatement(patch);
        // cStmt.execute();
        log.info("Patch succeeded");
        status = true;
    } catch (NullPointerException npe) {
        log.error("Caught NullPointerException", npe);
    } catch (Throwable e) {
        log.error(e.toString());
    } finally {
        DbUtil.closeSafely(cStmt);
        DbUtil.closeSafely(c);
    }

    return status;
}

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

private String filterEmptyLine(String content) {
    final StringBuilder sb = new StringBuilder();
    Scanner scanner = null;/*from  w w  w . j a v a 2s .c  o  m*/
    try {
        scanner = new Scanner(content);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line != null) {
                // remove extra space at line's end
                line = StringUtils.stripEnd(line, " ");
                if (line.isEmpty()) {
                    line = " ";
                }
            }
            sb.append(line).append('\n');
        }
    } finally {
        if (null != scanner) {
            scanner.close();
        }
    }

    return sb.toString();
}

From source file:edu.gmu.isa681.ctn.EncodedChannel.java

public EncodedChannel(String name, InputStream in, int inboundCapacity, OutputStream out, int outboundCapacity)
        throws UnsupportedEncodingException {
    this.name = name;
    this.sin = new Scanner(new BufferedReader(new InputStreamReader(in, "UTF-8")));
    this.sout = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));

    startHandlers(inboundCapacity, outboundCapacity);
}

From source file:com.it.j2ee.cache.ehcache.cluster.client1.Client1.java

@SuppressWarnings("resource")
@Test//from   w  ww .  ja v a2s .  c o m
public void demo() {
    cache = ehcacheManager.getCache(CACHE_NAME);

    // ?cache?
    String key = "foo";
    String value = "boo";
    List<Element> list = Lists.newArrayList(new Element(key, value), new Element("foo1", "value1"),
            new Element("22", "5555555"));

    put(key, value);
    Object result = get(key);
    assertThat(result).isEqualTo(value);

    cache.putAll(list);
    assertThat(cache.getSize()).isEqualTo(3);

    System.out.println("Cluster1: (q?)");

    int i = 0;
    do {
        // cluster2cluster1??
        System.out.println("cluster1-key:");
        if ("q".equals(key)) {
            System.exit(0);
        }
        key = new Scanner(System.in).nextLine();
        System.out.println("cluster1-value:");
        value = new Scanner(System.in).nextLine();
        put(key, value);

        // cluster2??
        System.out.println("?cluster2-key:");
        key = new Scanner(System.in).nextLine();
        result = get(key);
        System.out.println("?cluster2-value:" + result);
        i++;
    } while (i < 10);

    // ???
    new Scanner(System.in).nextLine();

}

From source file:BitLottoVerify.java

public static Map<String, Long> getPaymentsBlockExplorer(String addr) throws Exception {
    URL u = new URL("http://blockexplorer.com/address/" + addr);
    Scanner scan = new Scanner(u.openStream());

    TreeMap<String, Long> map = new TreeMap<String, Long>();

    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        StringTokenizer stok = new StringTokenizer(line, "\"#");
        while (stok.hasMoreTokens()) {
            String token = stok.nextToken();
            if (token.startsWith("/tx/")) {
                String tx = token.substring(4);
                line = scan.nextLine();//w w  w  .j ava  2  s . c o  m
                line = scan.nextLine();
                StringTokenizer stok2 = new StringTokenizer(line, "<>");
                stok2.nextToken();
                double amt = Double.parseDouble(stok2.nextToken());
                long amt_l = (long) Math.round(amt * 1e8);
                map.put(tx, amt_l);

            }
        }
    }
    return map;
}

From source file:com.mgmtp.perfload.perfalyzer.util.MarkersReader.java

public List<Marker> readMarkers() throws IOException {
    Map<String, Marker> markers = new LinkedHashMap<>();

    StrTokenizer tokenizer = StrTokenizer.getCSVInstance();
    tokenizer.setDelimiterChar(DELIMITER);

    try (FileInputStream fis = new FileInputStream(inputFile)) {

        for (Scanner scanner = new Scanner(fis.getChannel()); scanner.hasNext();) {
            String line = scanner.nextLine();
            if (line.startsWith("#")) {
                continue;
            }//from  w  w  w  .ja va  2s  . c  o m

            tokenizer.reset(line);

            List<String> tokenList = tokenizer.getTokenList();

            if (MARKER.equals(tokenList.get(COL_MARKER))) {
                // no whitespace allowed in marker in order to avoid issues in HTML
                String markerName = tokenList.get(COL_MARKER_NAME).replaceAll("\\s+", "_");
                String markerType = tokenList.get(COL_MARKER_TYPE);
                long timeMillis = Long.parseLong(tokenList.get(COL_TIMESTAMP));

                switch (markerType) {
                case MARKER_LEFT: {
                    Marker marker = new Marker(markerName);
                    markers.put(markerName, marker);
                    marker.setLeftMillis(timeMillis);
                    break;
                }
                case MARKER_RIGHT: {
                    Marker marker = markers.get(markerName);
                    marker.setRightMillis(timeMillis);
                    break;
                }
                default:
                    throw new IllegalStateException("Invalid marker type: " + markerType);
                }
            }
        }

        return markers.values().stream().map(marker -> {
            marker.calculateDateTimeFields(testStart);
            return marker;
        }).collect(toList());
    }
}

From source file:mini_mirc_client.Mini_mirc_client.java

private static void perform(TTransport transport, miniIRC.Client client) throws TException {
    //private static void perform () throws TException {
    boolean exit = false;
    Scanner input = new Scanner(System.in);

    generateUname();/*from  w ww  .jav  a  2  s. c om*/
    //auto-regis
    int res;
    synchronized (transport) {
        transport.open();
        res = client.regUser(username);
        transport.close();

        if (res == 0) {
            System.out.println("# Registered user: " + username);
        } else {
            System.out.println("!!!: Unidentified error on register!");

            generateUname();
            transport.open();
            res = client.regUser(username);
            if (res == 0)
                System.out.println("# Registered user: " + username);
            transport.close();
        }
    }

    while (!exit) {
        System.out.print("> ");
        String command = input.nextLine();

        String resSplit[] = command.split(" ", 2);
        String commandWord = resSplit[0].toUpperCase();

        synchronized (transport) {
            transport.open();

            switch (commandWord) {
            case "/NICK":
                System.out.println("# Registering user: " + resSplit[1]);
                res = client.regUser(resSplit[1]);

                if (res == 0) {
                    System.out.println("# Registered user: " + resSplit[1]);
                    username = resSplit[1];
                } else if (res == 2) {
                    System.out.println("# Login as user: " + resSplit[1]);
                    username = resSplit[1];
                } else {
                    System.out.println("!!!: Unidentified error on register!");
                }
                break;
            case "/JOIN":
                System.out.println("# Checking channel: " + resSplit[1]);

                res = client.join(username, resSplit[1]);
                if (res == 0 || res == 2) {
                    System.out.println("# Joined channel: " + resSplit[1]);
                } else {
                    if (res == 1) {
                        System.out.println("!!!: Channel " + resSplit[1] + " already joined!");
                    } else {
                        System.out.println("!!!: code #" + res + " on channel join");
                    }
                }

                break;
            case "/LEAVE":
                if (username.isEmpty()) {
                    System.out.println("!!!: Unregistered user");
                } else {
                    System.out.println("# " + username + " exiting channel " + resSplit[1]);
                    res = client.leave(username, resSplit[1]);
                    if (res == 0)
                        System.out.println("# Success");
                    else
                        System.out.println("!!!: Channel error!");
                }
                break;

            case "/EXIT":
                System.out.println("# " + username + " closing...");

                res = client.exit(username);
                if (res == 0) {
                    System.out.println("# Exit success");
                    username = "";
                    exit = true;
                    update = false;
                } else {
                    System.out.println("!!!: Channel error! Error code #" + res);
                }
                break;

            default:
                if (resSplit[0].startsWith("@")) { // message to channel 
                    res = client.message(username, resSplit[0].substring(1), resSplit[1]);
                    if (res == 0) {
                        System.out.println("# Msg to " + resSplit[0].substring(1) + " sent");
                    } else if (res == 2) {
                        System.out.println("!!!: Not member of channel " + resSplit[0].substring(1));
                    }
                } else {

                    res = client.message(username, "*", command);
                    if (res == 0) {
                        System.out.println("# Msg to all channels sent");
                    } else {
                        System.out.println("!!!: Connection problemo?");
                    }

                }
                break;
            }
            transport.close();

        }
        showMsg();
    }

}

From source file:nu.yona.server.rest.RestClientErrorHandler.java

private static String convertStreamToString(InputStream is) {
    @SuppressWarnings("resource") // It's not on us to close this stream
    java.util.Scanner s = new Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}