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:Main.java

public static void main(String[] args) {

    String s = "java2s.com 1 + 1 = 2.0";

    Scanner scanner = new Scanner(s);

    // find a string of world, with horizon of 10
    System.out.println(scanner.findWithinHorizon("com", 10));

    // find a string of world, with horizon of 20
    System.out.println(scanner.findWithinHorizon("=", 20));

    // print the rest of the string
    System.out.println(scanner.nextLine());

    scanner.close();/*from  ww w.jav a  2s . c  o  m*/
}

From source file:com.vmware.fdmsecprotomgmt.PasswdEncrypter.java

/**
 * Entry point into this Class/*w  ww .  ja v a2s  .  c o m*/
 */
public static void main(String[] args) {
    boolean validVals = false;
    String secretKey = "";
    String esxi_pwd = "";
    System.out.println("This Utility program would help you to ENCRYPT password with a given secretKey");
    Scanner in = new Scanner(System.in);
    System.out.print("Enter ESXi host password:");
    esxi_pwd = in.nextLine().trim();
    if (esxi_pwd.equals("")) {
        System.err.println("Invalid password entry, please try again ...");
    } else {
        System.out.println(
                "Enter SecretKey to be used for encrypting ESXi Password. MUST NOT exceed 16 characters,"
                        + "and should be different from ESXi password; for better security");
        secretKey = in.nextLine().trim();

        if (secretKey.equals("")) {
            System.err.println("Invalid SecretKey entry, please try again ...");
        } else if (secretKey.length() > STD_KEYSIZE) {
            System.err.println("SecretKey can NOT exceed 16 characters. Please try again");
        } else if (secretKey.length() < STD_KEYSIZE) {
            int remainingChars = STD_KEYSIZE - secretKey.length();
            while (remainingChars > 0) {
                secretKey = secretKey + PADDING_ARRAY[remainingChars];
                --remainingChars;
            }
        }
        if (secretKey.length() == STD_KEYSIZE) {
            validVals = true;
        }
    }

    // Go for encrypting the password with provided SecretKey
    if (validVals) {
        String encryptedStr = encrypt(secretKey, esxi_pwd);
        if ((!encryptedStr.equals(""))) {
            // Validate that on decrypt, you would receive the same password
            String decryptedStr = decrypt(secretKey, encryptedStr);
            if (!decryptedStr.equals("")) {
                if (decryptedStr.equals(esxi_pwd)) {
                    System.out.println("Successfully encrypted the password");
                    System.out.println("----------------------------------------------------------------");
                    System.out.println("ESXi Password: " + esxi_pwd);
                    System.out.println("Your Secret key: " + secretKey);
                    System.out.println("Encrypted String for the password: " + encryptedStr);
                    System.out.println("[TESTED] Decrypted string: " + decryptedStr);
                    System.out.println("----------------------------------------------------------------");
                    System.out.println("**** NOTE ****");
                    System.out.println(
                            "Please remember the secretkey, which is later needed when running TLS-Configuration script");
                } else {
                    System.err.println("Failed to match the password with decrypted string");
                }
            } else {
                System.err.println("Failed to decrypt the encrypted string");
            }
        } else {
            System.err.println("Failed to encrypt the provided password");
        }
    }
    // close the scanner
    in.close();
}

From source file:edu.usf.cutr.obascs.OBASCSMain.java

public static void main(String[] args) {

    String logLevel = null;/* w ww.ja va  2s  . co m*/
    String outputFilePath = null;
    String inputFilePath = null;
    String spreadSheetId = null;
    Logger logger = Logger.getInstance();

    Options options = CommandLineUtil.createCommandLineOptions();
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        logLevel = CommandLineUtil.getLogLevel(cmd);
        logger.setup(logLevel);
        outputFilePath = CommandLineUtil.getOutputPath(cmd);
        spreadSheetId = CommandLineUtil.getSpreadSheetId(cmd);

        inputFilePath = CommandLineUtil.getInputPath(cmd);
    } catch (ParseException e1) {
        logger.logError(e1);
    } catch (FileNotFoundException e) {
        logger.logError(e);
    }

    Map<String, String> agencyMap = null;
    try {
        agencyMap = FileUtil.readAgencyInformantions(inputFilePath);
    } catch (IOException e1) {
        logger.logError(e1);
    }

    logger.log("Consolidation started...");
    logger.log("Trying as public url");

    ListFeed listFeed = null;
    Boolean authRequired = false;
    try {
        listFeed = SpreadSheetReader.readPublicSpreadSheet(spreadSheetId);
    } catch (IOException e) {
        logger.logError(e);
    } catch (ServiceException e) {
        logger.log("Authentication Required");
        authRequired = true;
    }

    if (listFeed == null && authRequired == true) {
        Scanner scanner = new Scanner(System.in);
        String userName, password;
        logger.log("UserName:");
        userName = scanner.nextLine();
        logger.log("Password:");
        password = scanner.nextLine();
        scanner.close();

        try {
            listFeed = SpreadSheetReader.readPrivateSpreadSheet(userName, password, spreadSheetId);
        } catch (IOException e) {
            logger.logError(e);
        } catch (ServiceException e) {
            logger.logError(e);
        }
    }

    if (listFeed != null) {
        //Creating consolidated stops
        String consolidatedString = FileConsolidator.consolidateFile(listFeed, agencyMap);
        try {
            FileUtil.writeToFile(consolidatedString, outputFilePath);
        } catch (FileNotFoundException e) {
            logger.logError(e);
        }

        //Creating sample stop consolidation script config file
        try {
            String path = ClassLoader.getSystemClassLoader()
                    .getResource(GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE).getPath();
            String configXml = FileUtil.readFile(URLUtil.trimSpace(path));
            configXml = ConfigFileGenerator.generateStopConsolidationScriptConfigFile(configXml, agencyMap);
            path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE;
            FileUtil.writeToFile(configXml, path);
        } catch (IOException e) {
            logger.logError(e);
        }

        //Creating sample real-time config file
        try {
            String path = ClassLoader.getSystemClassLoader()
                    .getResource(GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE).getPath();
            String configXml = FileUtil.readFile(URLUtil.trimSpace(path));
            configXml = ConfigFileGenerator.generateSampleRealTimeConfigFile(configXml, agencyMap);
            path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE;
            FileUtil.writeToFile(configXml, path);
        } catch (IOException e) {
            logger.logError(e);
        }
    } else {
        logger.logError("Cannot write files");
    }

    logger.log("Consolidation finished...");

}

From source file:mx.uaq.facturacion.enlace.system.EmailSystemTest.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args//w ww.  jav a 2s  .  co  m
 *            - command line arguments
 */
public static void main(final String... args) {

    LOGGER.info(HORIZONTAL_LINE + "\n" + "\n          Welcome to Spring Integration!                 " + "\n"
            + "\n    For more information please visit:                   "
            + "\n    http://www.springsource.org/spring-integration       " + "\n" + HORIZONTAL_LINE);

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:email-facturas.poller.xml", "classpath:facturacion-integration.xml");

    context.registerShutdownHook();

    final Scanner scanner = new Scanner(System.in);

    LOGGER.info(HORIZONTAL_LINE + "\n" + "\n    Please press 'q + Enter' to quit the application.    " + "\n"
            + HORIZONTAL_LINE);

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        }

    }

    LOGGER.info("Exiting application...bye.");

    System.exit(0);
}

From source file:com.bluexml.tools.miscellaneous.Translate.java

/**
 * @param args//from  w  w  w.j av a 2s. c om
 */
public static void main(String[] args) {
    System.out.println("Translate.main() 1");
    Console console = System.console();

    System.out.println("give path to folder that contains properties files");
    Scanner scanIn = new Scanner(System.in);

    try {
        // TODO Auto-generated method stub
        String sWhatever;

        System.out.println("Translate.main() 2");
        sWhatever = scanIn.nextLine();
        System.out.println("Translate.main() 3");

        System.out.println(sWhatever);

        File inDir = new File(sWhatever);

        FilenameFilter filter = new FilenameFilter() {

            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith("properties");
            }
        };
        File[] listFiles = inDir.listFiles(filter);
        for (File file : listFiles) {

            prapareFileToTranslate(file, inDir);

        }

        System.out.println("please translate text files and press enter");
        String readLine = scanIn.nextLine();
        System.out.println("Translate.main() 4");
        for (File file : listFiles) {

            File values = new File(file.getParentFile(), file.getName() + ".txt");
            writeBackValues(values, file);
            values.delete();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        scanIn.close();
    }

}

From source file:de.dakror.scpuller.SCPuller.java

public static void main(String[] args) {
    new File(System.getProperty("user.home") + "/.dakror/SCPuller").mkdirs();
    new File(System.getProperty("user.home") + "/.dakror/SCPuller/download").mkdir();
    Scanner scanner = new Scanner(System.in);

    loadDownloadedSongs();//www . j  a  v  a 2s  .c om

    try {
        while (true) {
            String line = scanner.nextLine().trim();
            download(line);

            saveDownloadedSongs();
        }
    } finally {
        scanner.close();
    }
}

From source file:URLConnectionTest.java

public static void main(String[] args) {
    try {/*from ww  w .  j av  a  2s. c  om*/
        String urlName;
        if (args.length > 0)
            urlName = args[0];
        else
            urlName = "http://java.sun.com";

        URL url = new URL(urlName);
        URLConnection connection = url.openConnection();

        // set username, password if specified on command line

        if (args.length > 2) {
            String username = args[1];
            String password = args[2];
            String input = username + ":" + password;
            String encoding = base64Encode(input);
            connection.setRequestProperty("Authorization", "Basic " + encoding);
        }

        connection.connect();

        // print header fields

        Map<String, List<String>> headers = connection.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            String key = entry.getKey();
            for (String value : entry.getValue())
                System.out.println(key + ": " + value);
        }

        // print convenience functions

        System.out.println("----------");
        System.out.println("getContentType: " + connection.getContentType());
        System.out.println("getContentLength: " + connection.getContentLength());
        System.out.println("getContentEncoding: " + connection.getContentEncoding());
        System.out.println("getDate: " + connection.getDate());
        System.out.println("getExpiration: " + connection.getExpiration());
        System.out.println("getLastModifed: " + connection.getLastModified());
        System.out.println("----------");

        Scanner in = new Scanner(connection.getInputStream());

        // print first ten lines of contents

        for (int n = 1; in.hasNextLine() && n <= 10; n++)
            System.out.println(in.nextLine());
        if (in.hasNextLine())
            System.out.println(". . .");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Service.java

public static void main(String[] args) {

    StringWriter sw = new StringWriter();
    try {/*from   w ww  .j  a v  a  2 s . c om*/
        JsonGenerator g = factory.createGenerator(sw);
        g.writeStartObject();
        g.writeNumberField("code", 200);
        g.writeArrayFieldStart("languages");
        for (Language l : Languages.get()) {
            g.writeStartObject();
            g.writeStringField("name", l.getName());
            g.writeStringField("locale", l.getLocaleWithCountryAndVariant().toString());
            g.writeEndObject();
        }
        g.writeEndArray();
        g.writeEndObject();
        g.flush();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    String languagesResponse = sw.toString();

    String errorResponse = codeResponse(500);
    String okResponse = codeResponse(200);

    Scanner sc = new Scanner(System.in);
    while (sc.hasNextLine()) {
        try {
            String line = sc.nextLine();
            JsonParser p = factory.createParser(line);
            String cmd = "";
            String text = "";
            String language = "";
            while (p.nextToken() != JsonToken.END_OBJECT) {
                String name = p.getCurrentName();
                if ("command".equals(name)) {
                    p.nextToken();
                    cmd = p.getText();
                }
                if ("text".equals(name)) {
                    p.nextToken();
                    text = p.getText();
                }
                if ("language".equals(name)) {
                    p.nextToken();
                    language = p.getText();
                }
            }
            p.close();

            if ("check".equals(cmd)) {
                sw = new StringWriter();
                JsonGenerator g = factory.createGenerator(sw);
                g.writeStartObject();
                g.writeNumberField("code", 200);
                g.writeArrayFieldStart("matches");
                for (RuleMatch match : new JLanguageTool(Languages.getLanguageForShortName(language))
                        .check(text)) {
                    g.writeStartObject();

                    g.writeNumberField("offset", match.getFromPos());

                    g.writeNumberField("length", match.getToPos() - match.getFromPos());

                    g.writeStringField("message", substituteSuggestion(match.getMessage()));

                    if (match.getShortMessage() != null) {
                        g.writeStringField("shortMessage", substituteSuggestion(match.getShortMessage()));
                    }

                    g.writeArrayFieldStart("replacements");
                    for (String replacement : match.getSuggestedReplacements()) {
                        g.writeString(replacement);
                    }
                    g.writeEndArray();

                    Rule rule = match.getRule();

                    g.writeStringField("ruleId", rule.getId());

                    if (rule instanceof AbstractPatternRule) {
                        String subId = ((AbstractPatternRule) rule).getSubId();
                        if (subId != null) {
                            g.writeStringField("ruleSubId", subId);
                        }
                    }

                    g.writeStringField("ruleDescription", rule.getDescription());

                    g.writeStringField("ruleIssueType", rule.getLocQualityIssueType().toString());

                    if (rule.getUrl() != null) {
                        g.writeArrayFieldStart("ruleUrls");
                        g.writeString(rule.getUrl().toString());
                        g.writeEndArray();
                    }

                    Category category = rule.getCategory();
                    CategoryId catId = category.getId();
                    if (catId != null) {
                        g.writeStringField("ruleCategoryId", catId.toString());

                        g.writeStringField("ruleCategoryName", category.getName());
                    }

                    g.writeEndObject();
                }
                g.writeEndArray();
                g.writeEndObject();
                g.flush();
                System.out.println(sw.toString());
            } else if ("languages".equals(cmd)) {
                System.out.println(languagesResponse);
            } else if ("quit".equals(cmd)) {
                System.out.println(okResponse);
                return;
            } else {
                System.out.println(errorResponse);
            }
        } catch (Exception e) {
            System.out.println(errorResponse);
        }
    }
}

From source file:EchoServer.java

public static void main(String[] args) {
    try {//w w  w.  j  av a 2 s .  c  o m
        // establish server socket
        ServerSocket s = new ServerSocket(8189);

        // wait for client connection
        Socket incoming = s.accept();
        try {
            InputStream inStream = incoming.getInputStream();
            OutputStream outStream = incoming.getOutputStream();

            Scanner in = new Scanner(inStream);
            PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);

            out.println("Hello! Enter BYE to exit.");

            // echo client input
            boolean done = false;
            while (!done && in.hasNextLine()) {
                String line = in.nextLine();
                out.println("Echo: " + line);
                if (line.trim().equals("BYE"))
                    done = true;
            }
        } finally {
            incoming.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:javaapplicationclientrest.JavaApplicationClientRest.java

/**
 * @param args the command line arguments
 *///from   w w  w  . ja  va 2  s .c o  m
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    ControllerCliente controller = new ControllerCliente();
    while (true) {
        controller.getMenu();

        int op = 0;
        try {
            op = Integer.parseInt(input.nextLine());
        } catch (Exception e) {
        }

        //input.nextLine();
        switch (op) {
        case 1:
            controller.listarNoticias();
            break;
        case 2:

            System.out.println("Informe o titulo: ");
            String titulo = input.nextLine();
            if (titulo.trim().equals("")) {
                System.out.println("Ttulo invlido");
                break;
            }
            System.out.println("Informe o autor: ");
            String autor = input.nextLine();
            if (autor.trim().equals("")) {
                System.out.println("Autor invlido");
                break;
            }
            System.out.println("Informe o Conteudo: ");
            String conteudo = input.nextLine();
            if (conteudo.trim().equals("")) {
                System.out.println("Conteudo invlido");
                break;
            }
            //System.out.println(id);
            controller.cadastrarNoticia(titulo, autor, conteudo);
            break;

        case 3:

            try {
                System.out.println("Informe o id da notcia a ser removida: ");
                String idN = input.nextLine();
                Integer.parseInt(idN);
                controller.removerNoticia(idN);
            } catch (Exception e) {
                System.out.println("Numero invlido");
            }
            break;
        case 4:
            try {
                System.out.println("Informe o Id da notcia desejada:");
                String idN = input.nextLine();
                Integer.parseInt(idN);
                controller.getNoticia(idN);
            } catch (Exception e) {
                System.out.println("Id invlido");
                break;
            }
            break;
        case 5:
            try {
                System.out.println("Informe o Id da notcia para ser atualizada:");
                String idA = input.nextLine();
                Integer.parseInt(idA);
                System.out.println("Informe o novo titulo: ");
                String tituloN = input.nextLine();
                controller.atualizarNoticia(idA, tituloN);
            } catch (Exception e) {
                System.out.println("Id invlido");
            }
            break;

        default:
            System.out.println("Opo invlida. Escolha uma opo novamente");
            break;
        } // End switch
    } // End while

}