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:org.springframework.hateoas.alps.JacksonSerializationTests.java

private static String read(Resource resource) throws IOException {

    Scanner scanner = null;/*  w w w  .j av  a  2 s  .co  m*/

    try {

        scanner = new Scanner(resource.getInputStream());
        StringBuilder builder = new StringBuilder();

        while (scanner.hasNextLine()) {

            builder.append(scanner.nextLine());

            if (scanner.hasNextLine()) {
                builder.append("\n");
            }
        }

        return builder.toString();

    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

From source file:com.yoavst.quickapps.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/>//w w  w .j av  a  2s  . co  m
 * 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<>();
        parse(result, new Scanner(query), encoding);
    }
    return result;
}

From source file:com.team3637.service.ScheduleServiceMySQLImpl.java

@Override
public void initDB(String initScript) {
    String script = "";
    try {//w w  w  .  j  ava  2  s  . c  o m
        Scanner sc = new Scanner(new File(initScript));
        while (sc.hasNext())
            script += sc.nextLine();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    jdbcTemplateObject.execute(script);
}

From source file:com.joliciel.frenchTreebank.export.FtbPosTagMapperImpl.java

public FtbPosTagMapperImpl(File file, PosTagSet posTagSet) {
    this.posTagSet = posTagSet;
    Scanner scanner = null;/* www.  java  2  s .  c  om*/
    try {
        scanner = new Scanner(file);
        List<String> descriptors = new ArrayList<String>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            descriptors.add(line);
        }
        this.load(descriptors);
    } catch (FileNotFoundException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.siphyc.utils.Utilities.java

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if (!sc.hasNextInt(radix)) {
        return false;
    }/*from  ww w.j  a va2  s.c o  m*/
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

From source file:MediaLibrary.java

public MediaLibrary(String jsonFilename) {
    this.mediaFiles = new HashMap<String, MediaDescription>();
    count = 0;//w  ww .j  a  v  a 2s .c om

    Scanner ifstr = null;

    try {
        ifstr = new Scanner(new FileInputStream(jsonFilename));

        StringBuilder sb = new StringBuilder();

        while (ifstr.hasNext()) {
            sb.append(ifstr.next());
        }

        JSONObject obj = new JSONObject(sb.toString());

        for (String title : JSONObject.getNames(obj)) {
            JSONObject tobj = new JSONObject(obj.get(title).toString());

            MediaDescription md = new MediaDescription(tobj);

            mediaFiles.put(md.getTitle(), md);
        }

    } catch (FileNotFoundException fnfe) {
        System.out.println("File not found");
        fnfe.printStackTrace();
    } finally {
        ifstr.close();
    }

}

From source file:audiomanagershell.commands.FavCommand.java

@Override
public void execute() throws CommandException {
    Path file = Paths.get(this.pathRef.toString(), this.arg);

    if (!Files.exists(file))
        throw new FileNotFoundException(file.getFileName().toString());
    if (!Files.isRegularFile(file))
        throw new NotAFileException(file.getFileName().toString());

    List<String> validExtensions = Arrays.asList("wav", "mp3", "flac", "mp4");
    if (!validExtensions.contains(FilenameUtils.getExtension(file.toString())))
        throw new NotAudioFileException(file.toString());

    try (PrintWriter output = new PrintWriter(new FileWriter(favFile.toFile(), true));
            Scanner input = new Scanner(new FileReader(favFile.toString()))) {

        while (input.hasNextLine()) {
            if (input.nextLine().equals(file.toString())) {
                System.out.printf("File \"%s\" is already added to favorite List!%n", file);
                return;
            }/*from w ww .j  a va2 s. c  o m*/
        }
        System.out.printf("Added: \"%s\"%n", file);
        output.println(file);
    } catch (IOException ex) {
        throw new CommandException("Error related from I/O to file:" + favFile.toString());
    }
}

From source file:br.upf.contatos.tcp.Client.java

public static boolean comando(String line, ClientConnector tcpService) {

    if (line.equals("help")) {
        System.out.println("op=[ listar, incluir, editar, deletar, parar, cidade ], label = valor");
        System.out.println("Para sair digite: parar");

        return true;

    } else {//from ww  w .j a v  a2  s.  c o m

        tcpService.connect();
        String[] chamadas = line.split(",");
        String[] op = chamadas[0].split("=");

        switch (op[1]) {
        case "listar":

            for (ContatoBean cb : tcpService.getAll()) {
                //System.out.println(new JSONObject(cb));
                System.out.println("ID:" + cb.getId());
                System.out.println("Nome:" + cb.getNome());
                System.out.println("Email:" + cb.getEmail());
                System.out.println("Endereco:" + cb.getEndereco());
                System.out.println("Comp:" + cb.getComplemento());
                System.out.println("CEP:" + cb.getCep());
                System.out.println("Cidade:" + cb.getCidade());
                System.out.println("Estado:" + cb.getEstado());
                System.out.println("Email Alt.:" + cb.getEmailAlternativo());
                System.out.println("------------");
            }

            break;

        case "id":
            String idList;
            Scanner scan2 = new Scanner(System.in);
            System.out.println("Informe o id do contato  listar:");
            idList = scan2.nextLine();
            int numIdList = Integer.parseInt(idList);
            ContatoBean conbean = new ContatoBean();
            conbean.setId(numIdList);

            try {
                conbean = tcpService.getById(numIdList);
                System.out.println("O contato buscado : ");
                System.out.println(new JSONObject(conbean));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "incluir":
            String id;
            String nome;
            String email;
            String end;
            String comp;
            String cep;
            String cid;
            String est;

            Scanner scan = new Scanner(System.in);
            //System.out.printf("Digite o id:");   
            //id = scan.nextLine();                     *** Pegar ID Informado
            System.out.printf("Digite o nome:");
            nome = scan.nextLine();
            System.out.printf("Digite o email:");
            email = scan.nextLine();
            System.out.printf("Digite o endereco:");
            end = scan.nextLine();
            System.out.printf("Digite o complemento:");
            comp = scan.nextLine();
            System.out.printf("Digite o cep:");
            cep = scan.nextLine();
            System.out.printf("Digite a cidade:");
            cid = scan.nextLine();
            System.out.printf("Digite o estado:");
            est = scan.nextLine();

            ContatoBean c = new ContatoBean();
            int numCep = Integer.parseInt(cep);
            int numId = 0; // ***  ID Sequencial automatico
            //int idsec = Integer.parseInt(id); *** Pegar ID Informado
            c.setId(numId); //  ***  ID Sequencial automatico
            //c.setId(idsec);                   *** Pegar ID Informado
            c.setNome(nome);
            c.setEmail(email);
            c.setEndereco(end);
            c.setComplemento(comp);
            c.setCep(numCep);
            c.setCidade(cid);
            c.setEstado(est);
            try {
                c = tcpService.insert(c);
                System.out.println("O contato foi adicionado com Sucesso! Segue abaixo as campos informados: ");
                System.out.println(new JSONObject(c));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "editar":

            while (true) {
                String resp;
                String nummId;
                Scanner sca = new Scanner(System.in);
                System.out.println("Deseja alterar um contato? responda sim ou no");
                resp = sca.nextLine();
                if (resp.equals("sim")) {

                    System.out.println("Informe o id do contato  editar");
                    nummId = sca.nextLine();

                    ContatoBean contB = new ContatoBean();
                    int numIdEdi = Integer.parseInt(nummId);

                    do {
                        String opEditar;

                        System.out.print(
                                "Escolha os atributos  alterar (nome, email, endereco, complemento, cep, cidade, estado, parar): ");
                        opEditar = sca.nextLine();

                        if (opEditar.equals("parar")) {
                            break;
                        } else {
                            String id2 = null;
                            String nome2 = null;
                            String email2 = null;
                            String end2 = null;
                            String comp2 = null;
                            String cep2 = null;
                            String cid2 = null;
                            String est2;
                            ContatoBean contact = new ContatoBean();

                            try {
                                contact = tcpService.getById(numIdEdi);
                            } catch (RuntimeException e) {
                                System.out.println(e.getMessage());
                                break;
                            }

                            switch (opEditar) {

                            case "nome":
                                System.out.printf("Digite o nome:");
                                nome2 = sca.nextLine();
                                contact.setNome(nome2);
                                break;
                            case "email":
                                System.out.printf("Digite o email:");
                                email2 = sca.nextLine();
                                contact.setEmail(email2);
                                break;
                            case "endereco":
                                System.out.printf("Digite o endereco:");
                                end2 = sca.nextLine();
                                contact.setEndereco(end2);
                                break;
                            case "complemento":
                                System.out.printf("Digite o complemento:");
                                comp2 = sca.nextLine();
                                contact.setComplemento(comp2);
                                break;
                            case "cep":
                                System.out.printf("Digite o cep:");
                                cep2 = sca.nextLine();
                                int numCepEdit = Integer.parseInt(cep2);
                                contact.setCep(numCepEdit);
                                break;
                            case "cidade":
                                System.out.printf("Digite o cidade:");
                                cid2 = sca.nextLine();
                                contact.setCidade(cid2);
                                break;
                            case "estado":
                                System.out.printf("Digite o estado:");
                                est2 = sca.nextLine();
                                contact.setEstado(est2);
                                break;

                            }

                            try {
                                contact = tcpService.update(contact);
                                System.out.println(
                                        "O contato foi alterado! Segue abaixo suas informaes atualizadas: ");
                                System.out.println(new JSONObject(contact));
                            } catch (RuntimeException e) {
                                System.out.println(e.getMessage());
                            }
                        }
                    } while (true);

                } else {
                    break;
                }

            }
            break;
        case "cidade":
            String cidade;
            ArrayList cidade2 = new ArrayList();
            Scanner scanner = new Scanner(System.in);
            System.out.println("Informe a cidade  listar");
            cidade = scanner.nextLine();

            try {
                cidade2 = (ArrayList) tcpService.getByCidade(cidade);
                // System.out.println(new JSONObject(cidade2));
                System.out.println("Segue os contatos que moram na cidade de " + cidade + ":");
                for (Object cb : cidade2) {
                    System.out.println(new JSONObject(cb));
                }
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "deletar":
            String idDel;
            Scanner scann = new Scanner(System.in);
            System.out.println("Informe o id do contato  deletar");
            idDel = scann.next();
            int numIdDel = Integer.parseInt(idDel);
            ContatoBean cb = new ContatoBean();
            cb.setId(numIdDel);
            try {
                cb = tcpService.delete(numIdDel);
                System.out.println("O contato com o id" + numIdDel + " foi deletado!");
                System.out.println(new JSONObject(cb));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "parar":

            System.out.println("Encerrando Aplicao...");
            return false;
        }

    }

    return true;
}

From source file:org.springframework.hateoas.alps.JacksonSerializationTest.java

private static String read(Resource resource) throws IOException {

    Scanner scanner = null;/*from w  w  w  .  j av a  2 s  .  co m*/

    try {

        scanner = new Scanner(resource.getInputStream());
        StringBuilder builder = new StringBuilder();

        while (scanner.hasNextLine()) {

            builder.append(scanner.nextLine());

            if (scanner.hasNextLine()) {
                builder.append(System.getProperty("line.separator"));
            }
        }

        return builder.toString();

    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

From source file:key.access.manager.HttpHandler.java

public String connect(String url, ArrayList data) throws IOException {
    try {//from   w w w. j  ava 2 s  .c o  m
        // open a connection to the site
        URL connectionUrl = new URL(url);
        URLConnection con = connectionUrl.openConnection();
        // activate the output
        con.setDoOutput(true);
        PrintStream ps = new PrintStream(con.getOutputStream());
        // send your parameters to your site
        for (int i = 0; i < data.size(); i++) {
            ps.print(data.get(i));
            //System.out.println(data.get(i));
            if (i != data.size() - 1) {
                ps.print("&");
            }
        }

        // we have to get the input stream in order to actually send the request
        InputStream inStream = con.getInputStream();
        Scanner s = new Scanner(inStream).useDelimiter("\\A");
        String result = s.hasNext() ? s.next() : "";
        System.out.println(result);

        // close the print stream
        ps.close();
        return result;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return "error";
    } catch (IOException e) {
        e.printStackTrace();
        return "error";
    }
}