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:biblivre3.marcutils.MarcReader.java

public static Record marcToRecord(final String marc, final MaterialType mt, final RecordStatus status) {
    final String splitter = detectSplitter(marc);
    final String escaped = HtmlEntityEscaper.replaceHtmlEntities(marc);
    Scanner scanner = null;

    try {/*from w w w  .  java 2 s . com*/
        final ByteArrayInputStream bais = new ByteArrayInputStream(escaped.getBytes("UTF-8"));
        scanner = new Scanner(bais, "UTF-8");
    } catch (UnsupportedEncodingException uee) {
        log.error(uee.getMessage(), uee);
        scanner = new Scanner(escaped);
    }

    final List<String> text = new ArrayList<String>();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        if (line.trim().length() > 3) {
            text.add(line);
        }
    }

    final String tags[] = new String[text.size()];
    final String values[] = new String[text.size()];

    for (int i = 0; i < text.size(); i++) {
        final String line = text.get(i);
        if (!line.toUpperCase().startsWith("LEADER")) {
            tags[i] = line.substring(0, 3).toUpperCase();
            values[i] = line.substring(4, text.get(i).length()).trim();
        } else {
            tags[i] = line.substring(0, 6).toUpperCase();
            values[i] = line.substring(7, text.get(i).length()).trim();
        }
    }

    final Leader leader = setLeader(tags, values, mt, status);
    final MarcFactory factory = MarcFactory.newInstance();
    final Record record = factory.newRecord(leader);
    setControlFields(record, tags, values);
    setDataFields(record, tags, values, splitter);
    return record;
}

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

/**
 * visible width for the given string./*from  w w w  . jav  a  2s. co m*/
 *
 * for example: "abc\n1234"'s width is 4.
 *
 * @param string the given string
 * @return visible width
 */
private static int width(String string) {
    int maxWidth = 0;
    final Scanner scanner = new Scanner(new StringReader(string));
    try {
        while (scanner.hasNextLine()) {
            maxWidth = max(length(scanner.nextLine()), maxWidth);
        }
    } finally {
        scanner.close();
    }
    return maxWidth;
}

From source file:controller.Parser.java

static LP parse(File f) throws FileNotFoundException {
    Scanner s = new Scanner(f);
    Pattern p = Pattern.compile(dvarreg);

    HashMap<String, Integer> x = new HashMap<String, Integer>();
    HashMap<Integer, String> xReverse = new HashMap<Integer, String>();
    int xcol = 0;

    /* Get input size and names of the decision variables. */
    int constraints = -1; // Take the objective function into account.
    while (s.hasNextLine()) {
        String line = s.nextLine();

        if (line.trim().equals(""))
            continue;

        /* //from   w  w  w  .  j av a 2  s .c om
         * TODO: Beware, will now accept invalid
         * files with multiple objective functions.
         */
        /*            if (!validConstraint(line) && !validObj(line)) {
        String e = "Unsupported format in file " + f;
        throw new IllegalArgumentException(e);
                    } */

        Matcher m = p.matcher(line);

        while (m.find()) {
            String var = m.group(3);
            if (validVarName(var) && !x.containsKey(var)) {
                x.put(var, xcol);
                xReverse.put(xcol++, var);
            }
        }
        constraints++;
    }

    BigFraction[][] Ndata = new BigFraction[constraints][x.size()];
    for (int i = 0; i < Ndata.length; i++) {
        Arrays.fill(Ndata[i], BigFraction.ZERO);
    }
    BigFraction[] bdata = new BigFraction[constraints];
    BigFraction[] cdata = new BigFraction[x.size()];
    Arrays.fill(cdata, BigFraction.ZERO);

    s = new Scanner(f);

    String obj = s.nextLine();
    Matcher m = p.matcher(obj);

    while (m.find()) {
        String var = m.group(3);
        if (!x.containsKey(var))
            continue;

        String sign = m.group(1);
        if (sign == null)
            sign = "+";

        String coeffStr = m.group(2);
        BigFraction coeff;
        if (coeffStr == null) {
            coeff = BigFraction.ONE;
        } else {
            coeff = new BigFraction(Double.parseDouble(coeffStr));
        }
        if (sign.equals("-"))
            coeff = coeff.negate();

        cdata[x.get(var)] = coeff;
    }

    int row = 0;
    while (s.hasNextLine()) {
        String line = s.nextLine();
        String[] split = line.split("<=");
        if (line.trim().equals(""))
            continue;
        if (split.length != 2) {
            String e = "Unsupported format in file " + f;
            throw new IllegalArgumentException(e);
        }
        m = p.matcher(line);
        bdata[row] = new BigFraction(Double.parseDouble(split[1]));

        while (m.find()) {
            String var = m.group(3);
            if (!x.containsKey(var))
                continue;

            String sign = m.group(1);
            if (sign == null)
                sign = "+";

            String coeffStr = m.group(2);
            BigFraction coeff;
            if (coeffStr == null) {
                coeff = BigFraction.ONE;
            } else {
                coeff = new BigFraction(Double.parseDouble(coeffStr));
            }
            if (sign.equals("-"))
                coeff = coeff.negate();

            Ndata[row][x.get(var)] = coeff;
        }
        row++;
    }

    return new LP(new Array2DRowFieldMatrix<BigFraction>(Ndata), new ArrayFieldVector<BigFraction>(bdata),
            new ArrayFieldVector<BigFraction>(cdata), xReverse);
}

From source file:carmen.LocationResolver.java

protected static void loadNameAndAbbreviation(String filename, HashSet<String> fullName,
        HashMap<String, String> abbreviations, boolean secondColumnKey) throws FileNotFoundException {
    Scanner inputScanner = new Scanner(new FileInputStream(filename), "UTF-8");
    while (inputScanner.hasNextLine()) {
        String line = inputScanner.nextLine().toLowerCase();
        String[] splitString = line.split("\t");
        splitString[0] = splitString[0].trim();
        if (fullName != null)
            fullName.add(splitString[0]);
        if (abbreviations != null) {
            if (!secondColumnKey) {
                abbreviations.put(splitString[0], splitString[1]);
            } else {
                abbreviations.put(splitString[1], splitString[0]);
            }//from w  w w .j a  v a2s. c  o m
        }
    }
    inputScanner.close();
}

From source file:com.github.mavogel.ilias.utils.IOUtils.java

/**
 * Reads and parses a multiple choices from the user.<br>
 * Handles wrong inputs and ensures the choices are meaningful (lo <= up) and in
 * the range of the possible choices./*from   www  . ja v a 2s .c  om*/
 *
 * @param choices the possible choices
 * @return the choice of the user.
 */
public static List<Integer> readAndParseChoicesFromUser(final List<?> choices) {
    boolean isCorrectDigits = false, isCorrectRanges = false;
    String line = null;
    List<Integer> digits = null;
    List<String[]> ranges = null;

    Scanner scanner = new Scanner(System.in);
    while (!(isCorrectDigits && isCorrectRanges)) {
        try {
            LOG.info(
                    "Your choice: \n - Comma separated choices and/or ranges (e.g.: 1, 2, 4-6, 8, 10-15 -> or a combination) \n - The Wildcard 'A' for selecting all choices");
            line = scanner.nextLine();

            if (containsWildcard(line)) {
                return IntStream.range(0, choices.size()).mapToObj(Integer::valueOf)
                        .collect(Collectors.toList());
            }
            // == 1
            List<String> trimmedSplit = splitAndTrim(line);
            checkForInvalidCharacters(trimmedSplit);

            // == 2
            digits = parseDigits(trimmedSplit);
            isCorrectDigits = checkInputDigits(choices, digits);

            // == 3
            ranges = parseRanges(trimmedSplit);
            isCorrectRanges = checkRanges(choices, ranges);
        } catch (NumberFormatException nfe) {
            if (!isCorrectDigits) {
                LOG.error("'" + line + "' contains incorrect indexes! Try again");
            }
            if (!isCorrectRanges) {
                LOG.error("'" + line + "' contains incorrect ranges! Try again");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
    }

    return concatDigitsAndRanges(digits, ranges);
}

From source file:com.shieldsbetter.sbomg.Cli.java

private static Object parseSbomgV1(Scanner s) throws OperationException {
    if (!s.hasNextLine()) {
        throw new OperationException("Empty.");
    }//from  w w w  . ja  va 2s  .c o m

    String magicLine = s.nextLine();
    if (!magicLine.startsWith("sbomg-")) {
        throw new OperationException("Input must begin with 'sbomg-'.");
    }

    String version = magicLine.substring("sbomg-".length()).trim();
    if (version.isEmpty()) {
        throw new OperationException("Format version must follow 'sbomg-'.");
    } else if (!version.equals("v1")) {
        throw new OperationException("Unrecognized format version: " + version + ".  Must be 'v1'.");
    }

    String modelDescriptorFormatSpecifier = expectLine(s, "Expecting model format specifier.  Found EOF.")
            .trim();

    if (!modelDescriptorFormatSpecifier.equals("yaml")) {
        throw new OperationException(
                "Model format specifier must be 'yaml'. Was: " + modelDescriptorFormatSpecifier);
    }

    String yamlBlock = expectBlock(s, "yaml");
    Object modelDescriptorObject = new Yaml().load(yamlBlock);

    return modelDescriptorObject;
}

From source file:io.selendroid.standalone.android.impl.DefaultAndroidEmulator.java

private static Map<String, Integer> mapDeviceNamesToSerial() {
    Map<String, Integer> mapping = new HashMap<String, Integer>();
    CommandLine command = new CommandLine(AndroidSdk.adb());
    command.addArgument("devices");
    Scanner scanner;
    try {//w ww.ja v a2s.c o m
        scanner = new Scanner(ShellCommand.exec(command));
    } catch (ShellCommandException e) {
        return mapping;
    }
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d");
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            String serial = matcher.group(0);

            Integer port = Integer.valueOf(serial.replaceAll("emulator-", ""));
            TelnetClient client = null;
            try {
                client = new TelnetClient(port);
                String avdName = client.sendCommand("avd name");
                mapping.put(avdName, port);
            } catch (AndroidDeviceException e) {
                // ignore
            } finally {
                if (client != null) {
                    client.close();
                }
            }
        }
    }
    scanner.close();

    return mapping;
}

From source file:com.shieldsbetter.sbomg.Cli.java

private static String expectLine(Scanner input, String failureMessage) throws OperationException {
    String result = null;/*w  ww  .j  a  v  a 2 s.co m*/

    while ((result == null || result.isEmpty()) && input.hasNextLine()) {
        result = input.nextLine();
    }

    if (result == null || result.isEmpty()) {
        throw new OperationException(failureMessage);
    }

    return result;
}

From source file:io.selendroid.android.impl.DefaultAndroidEmulator.java

private static Map<String, Integer> mapDeviceNamesToSerial() {
    Map<String, Integer> mapping = new HashMap<String, Integer>();
    CommandLine command = new CommandLine(AndroidSdk.adb());
    command.addArgument("devices");
    Scanner scanner;
    try {//from w  w  w . ja  v a2 s . com
        scanner = new Scanner(ShellCommand.exec(command));
    } catch (ShellCommandException e) {
        return mapping;
    }
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d");
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            String serial = matcher.group(0);

            Integer port = Integer.valueOf(serial.replaceAll("emulator-", ""));
            TelnetClient client = null;
            try {
                client = new TelnetClient(port);
                String avdName = client.sendCommand("avd name");
                mapping.put(avdName, port);
            } catch (AndroidDeviceException e) {
                // ignore
            } finally {
                if (client != null) {
                    client.close();
                }
            }
            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            try {
                socket = new Socket("127.0.0.1", port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                if (in.readLine() == null) {
                    throw new AndroidDeviceException("error");
                }

                out.write("avd name\r\n");
                out.flush();
                in.readLine();// OK
                String avdName = in.readLine();
                mapping.put(avdName, port);
            } catch (Exception e) {
                // ignore
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // do nothing
                }
            }
        }
    }
    scanner.close();

    return mapping;
}

From source file:etymology.config.CommandLineReader.java

public static void parseConfigFile(CommandLine cl, Configuration config) {
    String configFileName = cl.getOptionValue(CLOptions.CONFIG_FILE_OPTION);
    try {//from  w ww  .j  a v a  2  s.c o  m
        if (null == configFileName) {
            return;
        }
        File configFile = new File(configFileName);
        if (!configFile.exists()) {
            //Does not exist
            System.err.println("Config file \"" + configFileName + "\" does not exist!");
            System.exit(2);
        }
        //Parsing
        Scanner scanner = new Scanner(configFile);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains("#")) {
                line = line.substring(0, line.indexOf("#"));
            }
            line = line.trim();
            if (0 == line.length()) {
                continue;
            }
            parseLine(line, config, cl);
        }
    } catch (IOException ex) {
        Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
    }
}