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:gash.router.app.DemoApp.java

/**
 * sample application (client) use of our messaging service
 *
 * @param args//  www .  ja  v  a  2 s.c  o m
 */
public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("usage:  <ip address> <port no>");
        System.exit(1);
    }
    String ipAddress = args[0];
    int port = Integer.parseInt(args[1]);
    Scanner s = new Scanner(System.in);
    boolean isExit = false;
    try {
        MessageClient mc = new MessageClient(ipAddress, port);
        DemoApp da = new DemoApp(mc);
        int choice = 0;

        while (true) {
            System.out.println(
                    "Enter your option \n1. WRITE a file. \n2. READ a file. \n3. Update a File. \n4. Delete a File\n 5 Ping(Global)\n 6 Exit");
            choice = s.nextInt();
            switch (choice) {
            case 1: {
                System.out.println("Enter the full pathname of the file to be written ");
                String currFileName = s.next();
                File file = new File(currFileName);
                if (file.exists()) {
                    ArrayList<ByteString> chunkedFile = da.divideFileChunks(file);
                    String name = file.getName();
                    int i = 0;
                    String requestId = SupportMessageGenerator.generateRequestID();
                    for (ByteString string : chunkedFile) {
                        mc.saveFile(name, string, chunkedFile.size(), i++, requestId);
                    }
                } else {
                    throw new FileNotFoundException("File does not exist in this path ");
                }
            }
                break;
            case 2: {
                System.out.println("Enter the file name to be read : ");
                String currFileName = s.next();
                da.sendReadTasks(currFileName);
                //Thread.sleep(1000 * 100);
            }
                break;
            case 3: {
                System.out.println("Enter the full pathname of the file to be updated");
                String currFileName = s.next();
                File file = new File(currFileName);
                if (file.exists()) {
                    ArrayList<ByteString> chunkedFile = da.divideFileChunks(file);
                    String name = file.getName();
                    int i = 0;
                    String requestId = SupportMessageGenerator.generateRequestID();
                    for (ByteString string : chunkedFile) {
                        mc.updateFile(name, string, chunkedFile.size(), i++, requestId);
                    }
                    //Thread.sleep(10 * 1000);
                } else {
                    throw new FileNotFoundException("File does not exist in this path ");
                }
            }
                break;

            case 4:
                System.out.println("Enter the file name to be deleted : ");
                String currFileName = s.next();
                mc.deleteFile(currFileName);
                //Thread.sleep(1000 * 100);
                break;
            case 5:
                da.ping(1);
                break;
            case 6:
                isExit = true;
                break;
            default:
                break;
            }
            if (isExit)
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        CommConnection.getInstance().release();
        if (s != null)
            s.close();
    }
}

From source file:br.com.sicoob.cro.cop.batch.core.FileReadTasklet.java

@Override
public void process() {
    try {/*  w ww. ja v a2 s  .c  o  m*/
        List<Operation> operacoes = new ArrayList();
        InputStream source = this.getClass()
                .getResourceAsStream(this.context.getParameters().get("nomeArquivo").toString());
        Scanner scan = new Scanner(source);
        while (scan.hasNext()) {
            String[] dados = scan.next().split(";");
            Operation operacao = new Operation(dados[0], new BigDecimal(dados[1]), dados[2],
                    new BigDecimal(dados[3]));
            operacoes.add(operacao);
        }

        // calcula o percentual de provisionamento
        for (Operation operacao : operacoes) {
            LOG.info(operacao.toString());
        }
        scan.close();
        source.close();
    } catch (IOException ex) {
        Logger.getLogger(FileReadTasklet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.alibaba.openapi.client.util.URLEncodedUtils.java

/**
 * Returns a list of {@link NameValuePair NameValuePairs} as built from the
 * URI's query portion. For example, a URI of
 * http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three
 * NameValuePairs, one for a=1, one for b=2, and one for c=3.
 * <p>//from w ww . j  a  v a2  s. c om
 * This is typically useful while parsing an HTTP PUT.
 * 
 * @param uri
 *            uri to parse
 * @param encoding
 *            encoding to use while parsing the query
 */
public static List<NameValuePair> parse(final URI uri, final String encoding) {
    List<NameValuePair> result = Collections.emptyList();
    final String query = uri.getRawQuery();
    if (query != null && query.length() > 0) {
        result = new ArrayList<NameValuePair>();
        parse(result, new Scanner(query), encoding);
    }
    return result;
}

From source file:com.google.maps.android.utils.demo.MyItemReader.java

public List<MyItem> read(InputStream inputStream) throws JSONException {
    List<MyItem> items = new ArrayList<MyItem>();
    String json = new Scanner(inputStream).useDelimiter(REGEX_INPUT_BOUNDARY_BEGINNING).next();
    JSONArray array = new JSONArray(json);
    for (int i = 0; i < array.length(); i++) {
        JSONObject object = array.getJSONObject(i);
        double lat = object.getDouble("lat");
        double lng = object.getDouble("lng");
        items.add(new MyItem(lat, lng));
    }//  w  ww.j a  va2  s . c  o m
    return items;
}

From source file:com.taveloper.http.test.PwTest.java

private static String convertStreamToString(InputStream is) {
    return new Scanner(is).useDelimiter("\\A").next();
}

From source file:ir.ac.ut.snl.mrcd.InputConverter.java

public void convert(String filename) throws FileNotFoundException, UnsupportedEncodingException {
    int paddingSize = 49; //  50-1; 1 baraye '\n'

    File file = new File(filename);
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    Scanner scanner = new Scanner(bufferedReader);

    PrintWriter printWriter = new PrintWriter(filename + "-converted", "UTF-8");

    int n = scanner.nextInt();
    scanner.nextLine();//from ww w . java2 s.  co  m

    printWriter.write(StringUtils.leftPad(String.valueOf(n), paddingSize));
    printWriter.write('\n');

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        printWriter.write(StringUtils.leftPad(line, paddingSize));
        printWriter.write('\n');
    }

    scanner.close();
    printWriter.close();
}

From source file:com.asuraiv.coordination.menu.MainMenu.java

@Override
public void displayMenu() {

    boolean isContinue = true;

    while (isContinue) {

        System.out.println();/*from  ww w . j a  va 2  s  . c  o  m*/
        System.out.println();
        System.out.println("### Main MENU ###");
        System.out.println("1.  ?");
        System.out.println("2.  ");
        System.out.println("3.  ");
        System.out.println("99.  ");
        System.out.println();
        System.out.print(" ? >  ");

        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);

        switch (scanner.next()) {
        case "1":
            nextMenu = new RegistTaskMenu();
            isContinue = false;
            break;
        case "2":
            doTaskListUp();
            isContinue = true;
            break;
        case "3":
            doDeleteTasks();
            isContinue = true;
            break;
        case "99":
            //  
            isContinue = false;
            break;
        default:
            System.out.println("[WRONG!] .");
            isContinue = true;
            break;
        }
    }

    nextMenu.displayMenu();
}

From source file:com.chargebee.CSV.PhoneBook.PhoneBook2.PhoneBook.java

private void display(HashMap<String, ArrayList> map) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Search by : name/number?");
    String choice = sc.nextLine();
    System.out.println("Enter the " + choice + " : ");
    String param = sc.nextLine();

    if (choice.toLowerCase().equalsIgnoreCase("name")) {
        for (String key : map.keySet()) {
            if (key.toLowerCase().contains(param)) {
                ArrayList<Person> tempo = new ArrayList();
                tempo = map.get(key);/*from  w  ww  . j  ava 2  s  .  c om*/
                for (Person p : tempo) {
                    p.print();
                }
            }
        }
    } else if (choice.toLowerCase().equalsIgnoreCase("number")) {
        for (Map.Entry<String, ArrayList> entry : map.entrySet()) {
            ArrayList<Person> tempo = new ArrayList();
            tempo = entry.getValue();
            for (Person p : tempo) {
                if (p.getPhone().getHomeNumber().equalsIgnoreCase(param)
                        || p.getPhone().getMobileNumber().equalsIgnoreCase(param)
                        || p.getPhone().getWorkNumber().equalsIgnoreCase(param)) {
                    p.print();
                    break;
                }
                System.out.println("Phone Number not found!!");
            }
        }
    } else {
        System.out.println("Invalid Choice!!");
    }
}

From source file:pl.lewica.util.FileUtil.java

/**
 * Reads contents of a stream (e.g. SQL script) and splits it into separate statements.
 * IMPORTANT: The assumption is the statements are delimited by semicolons followed by new lines.
 * /*  w  w w .ja v  a2s.c o  m*/
 * If you are using this method to convert a string with multiple SQL queries to individual statements,
 * make sure the semicolon-new line sequence doesn't exist anywhere inside the SQL statements, perhaps
 * somewhere in the middle of long varchars or text fields as they would be treated as SQL statement
 * delimiters and you would therefore get unexpected results. 
 * 
 * The method might be useful on Android that is unable to e.g. create multiple tables in one go.
 */
public static List<String> convertStreamToStrings(InputStream is, String delimiter) {
    List<String> result = new ArrayList<String>();
    Scanner s = new Scanner(is);
    s.useDelimiter(delimiter);

    while (s.hasNext()) {
        String line = s.next().trim();
        if (line.length() > 0) {
            result.add(line);
        }
    }
    s.close();

    return result;
}

From source file:org.mobicents.servlet.restcomm.util.HttpUtils.java

public static Map<String, String> toMap(final HttpEntity entity) throws IllegalStateException, IOException {

    String contentType = null;/*from  ww w.  j ava  2 s. c  om*/
    String charset = null;

    contentType = EntityUtils.getContentMimeType(entity);
    charset = EntityUtils.getContentCharSet(entity);

    List<NameValuePair> parameters = null;
    if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) {
        parameters = URLEncodedUtils.parse(entity);
    } else {
        final String content = EntityUtils.toString(entity, HTTP.ASCII);
        if (content != null && content.length() > 0) {
            parameters = new ArrayList<NameValuePair>();
            URLEncodedUtils.parse(parameters, new Scanner(content), charset);
        }
    }

    final Map<String, String> map = new HashMap<String, String>();
    for (final NameValuePair parameter : parameters) {
        map.put(parameter.getName(), parameter.getValue());
    }
    return map;
}