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:formatMessage.VerifyInputScanner.java

public static BigDecimal verifyBigDecimal() {

    while (true) {
        Scanner input = new Scanner(System.in);
        try {//from w ww.  j a  v  a  2  s.  c  om
            BigDecimal verified = input.nextBigDecimal();

            return verified;
        } catch (InputMismatchException e) {
            System.out.println("Geen geldig nummer. Probeer opnieuw.");

        }
    }
}

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();//  www  .j  a v  a 2  s .c  o m

    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:csns.importer.parser.csula.StudentsParserImpl.java

/**
 * This parser handles data copy&pasted from an Excel file produced from GET
 * data. The format is expected to be <quarter cin first_name last_name ...>
 * where quarter is a 4-digit code. Currently we only process the first four
 * fields./* w  w  w.j a  v  a2 s  .  c o  m*/
 */
@Override
public List<ImportedUser> parse(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();

    Scanner scanner = new Scanner(text);
    while (scanner.hasNextLine()) {
        ImportedUser student = parseLine(scanner.nextLine());
        if (student != null)
            students.add(student);
    }
    scanner.close();

    return students;
}

From source file:com.sasav.blackjack.controller.BasicController.java

@RequestMapping(value = "/init", method = RequestMethod.GET)
public String initPage() {
    List users = commonDao.getAll(LoginDetails.class);
    if (users.isEmpty()) {
        File file = new File(getClass().getClassLoader().getResource("sql/insert-data.sql").getFile());
        StringBuilder query = new StringBuilder("");
        try (Scanner scanner = new Scanner(file)) {

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine() + "\n";
                query.append(line);/*from w  w w.  j ava  2s . c o m*/
            }

            scanner.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        commonDao.runQuery(query.toString());
    }
    return "login";
}

From source file:com.lithium.flow.filer.hash.ClientHashFiler.java

@Override
@Nonnull/*  w ww  .j a va2  s.  c  om*/
public String getHash(@Nonnull String path, @Nonnull String hash, @Nonnull String base) throws IOException {
    return client.call("hash " + path, input -> {
        Scanner scanner = new Scanner(input);
        scanner.next(); // size
        String value = scanner.next();
        scanner.next(); // status
        return BaseEncodings.of(base).encode(encoding.decode(value));
    });
}

From source file:com.ExtendedAlpha.SWI.SeparatorLib.Separator.java

public static String getStringFromStream(InputStream stream) {
    Scanner x = new Scanner(stream);
    String str = "";
    while (x.hasNextLine()) {
        str += x.nextLine() + "\n";
    }//from   w w w. java2s. c  o  m
    x.close();
    return str.trim();
}

From source file:com.google.mr4c.util.CustomFormat.java

private static List<String> extractNames(String pattern) {
    List<String> names = new ArrayList<String>();
    Scanner scanner = new Scanner(pattern);
    while (scanner.findWithinHorizon(VAR_REGEX, 0) != null) {
        MatchResult result = scanner.match();
        String val = result.group(1);
        names.add(val);
    }/*from  www.j ava 2  s .c  o  m*/
    return names;
}

From source file:net.dv8tion.jda.player.Playlist.java

public static Playlist getPlaylist(String url) {
    List<String> infoArgs = new LinkedList<>();
    infoArgs.addAll(YOUTUBE_DL_PLAYLIST_ARGS);
    infoArgs.add("--"); //Url separator. Deals with YT ids that start with --
    infoArgs.add(url);//from w  w w . ja v  a2s. c  o  m

    //Fire up Youtube-dl and get all sources from the provided url.
    List<AudioSource> sources = new ArrayList<>();
    Scanner scan = null;
    try {
        Process infoProcess = new ProcessBuilder().command(infoArgs).start();
        byte[] infoData = IOUtils.readFully(infoProcess.getInputStream(), -1, false);
        if (infoData == null || infoData.length == 0)
            throw new NullPointerException(
                    "The YT-DL playlist process resulted in a null or zero-length INFO!");

        String sInfo = new String(infoData);
        scan = new Scanner(sInfo);

        JSONObject source = new JSONObject(scan.nextLine());
        if (source.has("_type"))//Is a playlist
        {
            sources.add(new RemoteSource(source.getString("url")));
            while (scan.hasNextLine()) {
                source = new JSONObject(scan.nextLine());
                sources.add(new RemoteSource(source.getString("url")));
            }
        } else //Single source link
        {
            sources.add(new RemoteSource(source.getString("webpage_url")));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }

    //Now that we have all the sources we can create our Playlist object.
    Playlist playlist = new Playlist("New Playlist");
    playlist.sources = sources;
    return playlist;
}

From source file:com.wavemaker.spinup.web.VersionProvider.java

public String getVersion(ServletContext servletContext) throws IOException {
    String uploadDirName = servletContext.getRealPath(SpinupConstants.STUDIOD_UPLOAD_DIR);
    if (studioVersion != null) {
        return this.studioVersion;
    }//from  w  ww .  j a  v  a 2  s  .c  o  m
    ZipArchive studioZip = new ZipArchive(new LocalFolder(uploadDirName).getFile(SpinupConstants.STUDIO_FILE));
    InputStream configjs = studioZip.getFile("app/config.js").getContent().asInputStream();
    Scanner s = new Scanner(configjs);
    while (s.hasNext()) {
        String ln = s.nextLine();
        if (ln.contains("studioVersion:")) {
            this.studioVersion = ln.substring(ln.indexOf(":") + 1).replace(",", "").replace("'", "").trim();
            break;
        }
    }
    if (log.isInfoEnabled()) {
        log.info("*** Studio version is: " + this.studioVersion + "***");
    }
    configjs.close();
    return this.studioVersion;

}

From source file:com.liferay.blade.cli.util.Prompter.java

private static Optional<Boolean> _getBooleanAnswer(String questionWithPrompt, InputStream inputStream,
        PrintStream printStream, Optional<Boolean> defaultAnswer) {

    Optional<Boolean> answer = null;

    try (CloseShieldInputStream closeShieldInputStream = new CloseShieldInputStream(inputStream);
            Scanner scanner = new Scanner(closeShieldInputStream)) {

        while ((answer == null) || !answer.isPresent()) {
            printStream.println(questionWithPrompt);

            String readLine = null;

            while (((answer == null) || !answer.isPresent()) && !Objects.equals(answer, defaultAnswer)
                    && scanner.hasNextLine()) {

                readLine = scanner.nextLine();

                if (readLine != null) {
                    readLine = readLine.toLowerCase();

                    switch (readLine.trim()) {
                    case "y":
                    case "yes":
                        answer = Optional.of(true);

                        break;
                    case "n":
                    case "no":
                        answer = Optional.of(false);

                        break;
                    default:
                        if (defaultAnswer.isPresent()) {
                            answer = defaultAnswer;
                        } else {
                            printStream.println("Unrecognized input: " + readLine);

                            continue;
                        }/* w  ww. j a va2 s.co m*/

                        break;
                    }
                } else {
                    answer = defaultAnswer;
                }
            }
        }
    } catch (IllegalStateException ise) {
        throw new RuntimeException(ise);
    } catch (Exception exception) {
        if (defaultAnswer.isPresent()) {
            answer = defaultAnswer;
        }
    }

    return answer;
}