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:example.UserInitializer.java

private static List<User> readUsers(Resource resource) throws Exception {

    Scanner scanner = new Scanner(resource.getInputStream());
    String line = scanner.nextLine();
    scanner.close();/*from ww w .j a v  a  2  s .  com*/

    FlatFileItemReader<User> reader = new FlatFileItemReader<User>();
    reader.setResource(resource);

    DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
    tokenizer.setNames(line.split(","));
    tokenizer.setStrict(false);

    DefaultLineMapper<User> lineMapper = new DefaultLineMapper<User>();
    lineMapper.setFieldSetMapper(fields -> {

        User user = new User();

        user.setEmail(fields.readString("email"));
        user.setFirstname(capitalize(fields.readString("first")));
        user.setLastname(capitalize(fields.readString("last")));
        user.setNationality(fields.readString("nationality"));

        String city = Arrays.stream(fields.readString("city").split(" "))//
                .map(StringUtils::capitalize)//
                .collect(Collectors.joining(" "));
        String street = Arrays.stream(fields.readString("street").split(" "))//
                .map(StringUtils::capitalize)//
                .collect(Collectors.joining(" "));

        try {
            user.setAddress(new Address(city, street, fields.readString("zip")));
        } catch (IllegalArgumentException e) {
            user.setAddress(new Address(city, street, fields.readString("postcode")));
        }

        user.setPicture(new Picture(fields.readString("large"), fields.readString("medium"),
                fields.readString("thumbnail")));
        user.setUsername(fields.readString("username"));
        user.setPassword(fields.readString("password"));

        return user;
    });

    lineMapper.setLineTokenizer(tokenizer);

    reader.setLineMapper(lineMapper);
    reader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
    reader.setLinesToSkip(1);
    reader.open(new ExecutionContext());

    List<User> users = new ArrayList<>();
    User user = null;

    do {

        user = reader.read();

        if (user != null) {
            users.add(user);
        }

    } while (user != null);

    return users;
}

From source file:com.thalesgroup.sonar.plugins.tusar.utils.Utils.java

/**
 * Function that returns the extensions available in file open into the given Scanner
 * @param scanner// w  w  w.  ja  va  2s . com
 * @return An array of strings containing the file extensions
 */
public static String[] getExtensions(Scanner scanner) {
    List<String> extensions = new ArrayList<String>();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine().trim();
        if (line.startsWith(".")) {
            line = line.substring(1, line.length());
        }
        if (!line.isEmpty()) {
            extensions.add(line);
        }
    }
    return extensions.toArray(new String[extensions.size()]);
}

From source file:com.hsbc.srbp.commonMsg.test.Main.java

private static void createMessageDetails(final Scanner scanner, CommonMessageService service,
        AbstractApplicationContext context) {
    while (true) {
        System.out.print("\nEnter the Message`s name:");
        String message_name = scanner.nextLine();
        System.out.print("\nEnter the Message`s content:");
        String message_content = scanner.nextLine();
        System.out.print("\nEnter the Message`s status:");
        String message_status = scanner.nextLine();
        CommonMessage message = new CommonMessage();
        message.setMessage_name(message_name);
        message.setMessage_status(message_status);
        message.setMessage_content(message_content);
        //         message = service.createCommonMessage(message);
        System.out.println("Created message record with name: " + message);
        System.out.print("Do you want to create another message? (y/n)");
        String choice = scanner.nextLine();
        if (!"y".equalsIgnoreCase(choice))
            break;
    }//from w  ww.  j a  va2 s  .co  m
}

From source file:com.acmutv.ontoqa.ui.CliService.java

/**
 * Return the user input on {@code STDIN}.
 * @param message The message to ask input.
 * @return The user input./* w  w  w  . ja v  a2  s  .  c o  m*/
 */
public static String getInput(String message) {
    System.out.format("[%s]> %s: ", AppManifest.APP_NAME, message);
    String input;
    Scanner scanner = new Scanner(System.in);
    input = scanner.nextLine();
    return input;
}

From source file:medcheck.Medcheck.java

private static String getJSONString(File jsonFile) {
    String jsonString = "";
    try {/*from www .  j a  v a 2s .  c  o m*/
        Scanner fileScanner = new Scanner(jsonFile);
        boolean isFirstLine = true;
        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine().trim();
            if (!isFirstLine) {
                jsonString += " ";
            }
            isFirstLine = false;
            jsonString += line;
        }
    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
        e.printStackTrace();
        exit(1);
    }

    return jsonString;
}

From source file:amazonechoapi.AmazonEchoApi.java

private static boolean checkItemId(String itemId) throws IOException {
    File file = new File("Items.txt");
    boolean ret = false;
    try {/*from w  w  w. ja v a 2s.c o m*/
        if (!file.exists()) {
            file.createNewFile();
        }
        Scanner scanner = new Scanner(file);
        int lineNum = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            lineNum++;
            if (line.contains(itemId)) {
                ret = true;
            }
        }
    } catch (Exception e) {
        ret = false;
    }
    return ret;
}

From source file:com.microsoft.azure.storage.util.KeyVaultUtility.java

/**
 * Helper method to create a new secret on the KeyVault service.
 * //from   ww w  . j a  v  a2  s .  c  om
 * @param defaultKeyName
 *            The default key name to use if the user does not provide one
 * @return The keyID for the newly-created secret (or the existing secret,
 *         if one was passed in.)
 * @throws InterruptedException
 * @throws ExecutionException
 * @throws NoSuchAlgorithmException
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public static String createSecret(String defaultKeyName) throws InterruptedException, ExecutionException,
        NoSuchAlgorithmException, URISyntaxException, MalformedURLException {
    System.out.println("No secret specified in Utility class.");
    System.out.println("Please enter the name of a new secret to create in Key Vault.");
    System.out.println("WARNING: This will delete any existing secret with the same name.");
    System.out.println("If nothing is entered, the value \"" + defaultKeyName + "\" will be used.");

    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);
    String newSecretName = input.nextLine();

    if (newSecretName == null || newSecretName.isEmpty()) {
        newSecretName = defaultKeyName;
    }

    // Although it is possible to use keys (rather than secrets) stored in
    // Key Vault, this prevents caching.
    // Therefore it is recommended to use secrets along with a caching
    // resolver (see below).
    String keyID = KeyVaultUtility.SetUpKeyVaultSecret(newSecretName);

    System.out.println();
    System.out.println("Created a secret with ID: " + keyID);
    System.out.println("Copy the secret ID to App.config to reuse.");
    System.out.println();
    return keyID;
}

From source file:adviewer.util.JSONIO.java

/**
 * Take in file and return one string of json data
 * /*  ww  w. jav  a 2 s .c o  m*/
 * @return
 * @throws IOException
 */
public static String readJSONFile(File inFile) {
    String readFile = "";

    try {
        File fileIn = inFile;

        //if the file is not there then create the file
        if (fileIn.createNewFile()) {
            System.out.println(fileIn + " was created ");
        }

        FileReader fr = new FileReader(fileIn);
        Scanner sc = new Scanner(fr);

        while (sc.hasNext()) {
            readFile += sc.nextLine().trim();
        }

        return readFile;

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

    // System.out.println( readFile  );
    return readFile;
}

From source file:com.calamp.services.kinesis.events.writer.CalAmpEventWriter.java

public static List<CalAmpEvent> readEventsFromFile(String filePath) throws IOException {
    // Repeatedly send stock trades with a some milliseconds wait in between
    ArrayList<CalAmpEvent> eList = new ArrayList<CalAmpEvent>();
    Scanner scan = new Scanner(new FileReader(filePath));
    int count = 0;
    while (scan.hasNext()) {
        CalAmpEvent cae = CalAmpEvent.fromJsonAsString(scan.nextLine());
        eList.add(cae);/*w  ww . j a  v  a2s .  c o m*/

        if (count % CalAmpParameters.maxRecordsPerPut == 0) {
            System.out.println(cae.toJsonAsString());
        }
        count++;
        //System.out.println( CalAmpEvent.fromJsonAsString( cae.toJsonAsString()) );
    }
    if (scan != null) {
        scan.close();
    }
    return eList;
}

From source file:br.upf.contatos.udp.ClienteUDP.java

public static boolean comando(String[] args) throws SocketException, IOException {

    while (true) {
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        String[] comandos = line.split(" ");
        if (comandos[0].equals("help")) {
            System.out.println("Listar = Lista todos os contatos"
                    + "incluir = Inclui um contato, incluir nome NOMEtudoJUNTO email EMAIL end ENDERECO comp COPM cep CEP cid CID est EST \n"
                    + "editar  = edita um contato, escrever editar numeroDoID label VALORaSERalterado\n"
                    + "deletar = deletar id numero \n" + "parar   = finaliza conexao \n"
                    + "cidade  = lista por cidade escrever cidade nomeCidade\n"
                    + "Comandos seguidos de outras informacoes sempre separar por espaco, nomes tudo junto\n");

            return true;
        } else if (comandos[0].equals("parar")) {
            return false;
        } else {//from   w  w  w. j  a  v a2  s. com
            UDPConexao udpConnection = new UDPConexao(HOST, PORTA);
            udpConnection.connect();
            switch (comandos[0]) {
            case "listar": {
                for (ContatoBean cb : udpConnection.getAll()) {
                    System.out.println(new JSONObject(cb));
                }
                udpConnection.disconnect();

                break;
            } // TERMINA LISTAR
            case "incluir": {
                ContatoBean cb = new ContatoBean();
                if (comandos[1].equals("label=nome"))
                    cb.setNome(comandos[2]);
                if (comandos[3].equals("label=email"))
                    cb.setEmail(comandos[4]);
                if (comandos[5].equals("label=end"))
                    cb.setEndereco(comandos[6]);
                if (comandos[7].equals("label=comp"))
                    cb.setComplemento(comandos[8]);
                if (comandos[9].equals("label=cep"))
                    cb.setCep(Integer.parseInt(comandos[10]));
                if (comandos[11].equals("label=cid"))
                    cb.setCidade(comandos[12]);
                if (comandos[13].equals("label=est"))
                    cb.setEstado(comandos[14]);
                try {
                    cb = udpConnection.insert(cb);
                } catch (RuntimeException e) {
                    System.out.println(e.getMessage());
                }
                udpConnection.disconnect();
                break;
            } //TERMINA INCLUIR

            case "editar": {

                int numIdEdi = Integer.parseInt(args[1]);
                ContatoBean contact = new ContatoBean();
                contact = udpConnection.getById(numIdEdi);

                switch (args[2]) {
                case "id":
                    contact.setId(Integer.parseInt(args[3]));
                    break;
                case "nome":
                    contact.setNome(args[3]);
                    break;
                case "email":
                    contact.setEmail(args[3]);
                    break;
                case "end":
                    contact.setEndereco(args[3]);
                    break;
                case "comp":
                    contact.setComplemento(args[3]);
                    break;
                case "cep":
                    contact.setCep(Integer.parseInt(args[3]));
                    break;
                case "cid":
                    contact.setCidade(args[3]);
                    break;
                case "est":
                    contact.setEstado(args[3]);
                    break;

                }// FINALIZA CASE DE TROCA DE DADOS

                try {
                    contact = udpConnection.update(contact);
                    System.out.println(new JSONObject(contact));
                } catch (RuntimeException e) {
                    System.out.println(e.getMessage());
                }
                udpConnection.disconnect();
            } // TERMINA EDITAR 

            case "cidade": {
                ContatoBean cob = new ContatoBean();
                cob.setCidade(args[1]);
                try {
                    cob = udpConnection.getByCidade(cob);
                    System.out.println(new JSONObject(cob));
                } catch (RuntimeException e) {
                    System.out.println(e.getMessage());
                }

                udpConnection.disconnect();
                break;
            } //termina listar CIDADE

            case "deletar": {
                ContatoBean cb = new ContatoBean();
                cb.setId(Integer.parseInt(args[1]));
                try {
                    cb = udpConnection.delete(cb.getId());
                    System.out.println(new JSONObject(cb));
                } catch (RuntimeException e) {
                    System.out.println(e.getMessage());
                }

                udpConnection.disconnect();
                break;
            } //termina DELETAR

            }//TERMINA SWTICH
        } // TERMINA ELSE ANTES DO SWITCH    

    } //TERMINA WILHER TRUE
}