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:data_gen.Data_gen.java

public static String get_text_Dir() {
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the data source Directory: " + "\n");
    String Dir = s.nextLine().trim();
    return Dir;/*  w w  w . j ava  2s .  c o  m*/
}

From source file:com.amazonaws.auth.profile.internal.ProfilesConfigFileParser.java

/**
 * Loads the credentials from the given input stream.
 *
 * @param is input stream from where the profile details are read.
 * @throws IOException//from w  ww  .j a  v  a  2s  . co m
 */
private static Map<String, Profile> loadProfiles(InputStream is) throws IOException {
    Scanner scanner = new Scanner(is);
    AWSCredentials credentials = null;
    String profileName = null;
    String accessKey = null;
    String secretKey = null;
    String line = null;
    boolean accessKeyRead = false;
    boolean secretKeyRead = false;
    ProfileCredentialScannerState scannerState = ProfileCredentialScannerState.READ_CONFIG_NAME;
    HashMap<String, Profile> profilesByName = new HashMap<String, Profile>();

    try {
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            line = line.trim();

            if (line.isEmpty())
                continue;

            if (!line.startsWith("[") && !line.startsWith(AWS_ACCESS_KEY_ID)
                    && !line.startsWith(AWS_SECRET_ACCESS_KEY)) {
                LOG.info("Unsupported configuration setting: " + line);
                continue;
            }

            switch (scannerState) {
            case READ_CONFIG_NAME:
                profileName = parseProfileName(line);
                scannerState = ProfileCredentialScannerState.READ_KEY;
                break;
            case READ_KEY:
                if (line.startsWith(AWS_ACCESS_KEY_ID) && !accessKeyRead) {
                    accessKey = parseAccessKey(line);
                    accessKeyRead = true;
                } else if (!secretKeyRead) {
                    secretKey = parseSecretKey(line);
                    secretKeyRead = true;
                } else {
                    throw new AmazonClientException(
                            "Unable to load Amazon AWS Credentials. File not in proper format.");
                }
                break;
            }

            if (accessKeyRead && secretKeyRead) {

                assertParameterNotEmpty(profileName,
                        "Unable to load credentials into profile. ProfileName is empty. " + line);
                assertParameterNotEmpty(accessKey,
                        "Unable to load credentials into profile. AWS Access Key ID is empty. " + line);
                assertParameterNotEmpty(secretKey,
                        "Unable to load credentials into profile. AWS Secret Access Key is empty. " + line);

                credentials = new BasicAWSCredentials(accessKey, secretKey);
                profilesByName.put(profileName, new Profile(credentials));
                scannerState = ProfileCredentialScannerState.READ_CONFIG_NAME;
                accessKeyRead = false;
                secretKeyRead = false;
            }
        }
        if (scannerState != ProfileCredentialScannerState.READ_CONFIG_NAME || accessKeyRead || secretKeyRead) {
            throw new AmazonClientException(
                    "Unable to load credentials into profile. Profile Name or AWS Access Key ID or AWS Secret Access Key missing for a profile.");
        }

    } finally {
        scanner.close();
    }

    return profilesByName;
}

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

private static String expectBlock(Scanner input, String blockDesc) throws OperationException {
    String block = "";
    String curLine = "dummy";
    while (input.hasNextLine() && !curLine.isEmpty()) {
        curLine = input.nextLine();

        if (curLine.startsWith("% ")) {
            block += curLine.substring(("% ".length())) + "\n";
        } else {/*from ww  w. j  av  a 2  s.c  o m*/
            if (!curLine.trim().isEmpty()) {
                if (block.isEmpty()) {
                    throw new OperationException("Expecting a " + blockDesc
                            + "block line starting with '%' followed by a " + "space.");
                } else {
                    throw new OperationException(
                            "Text blocks must be " + "continued by block lines starting with '%' "
                                    + "followed by a space, or the block should be"
                                    + "terminated by EOF or a blank line.");
                }
            }
        }
    }

    if (block.isEmpty()) {
        throw new OperationException("Expecting a " + blockDesc + " block " + "starting with '%'. Found EOF.");
    }

    return block;
}

From source file:chatbot.Chatbot.java

/** **************************************************************************************************
 * Run with a given file/*w w w  . j  a v  a2  s  .co  m*/
 */
private static void run(String fname) throws IOException {

    List<String> documents = null;

    try {
        if (asResource)
            documents = TextFileUtil.readLines(fname, false);
        //documents = TextFileUtil.readFile(fname, false);
    } catch (IOException e) {
        System.out.println("Couldn't read document: " + fname + ". Exiting");
        return;
    }
    Chatbot cb;
    ResourceBundle resourceBundle = ResourceBundle.getBundle("corpora");
    if (asResource)
        cb = new Chatbot(documents, resourceBundle.getString("stopWordsDirectoryName"));
    else {
        cb = new Chatbot(resourceBundle.getString("stopWordsDirectoryName"));
        cb.readFile(fname);
    }

    System.out.println("Hi, I'm Cloudio, tell/ask me something. Type 'quit' to exit");

    if (isDevelopment) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("User: ");
            String input = scanner.nextLine();
            if (input.toLowerCase().trim().equals("quit"))
                break;
            System.out.print("Cloudio: ");
            System.out.println(cb.matchBestInput(input));
        }
    } else {
        while (true) {
            Console c = System.console();
            if (c == null) {
                System.err.println("No console.");
                System.exit(1);
            }
            String input = c.readLine("> ");
            if (input.toLowerCase().trim().equals("quit"))
                System.exit(1);
            System.out.println("Cloudio:" + cb.matchBestInput(input));
        }
    }
}

From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java

public static ArrayList<String> updateProjectJobFiles(File projectFile, File projectConfigDirectory,
        ArrayList<String> receivedJobNames) throws IOException {

    Scanner scanner = new Scanner(projectFile);

    ArrayList<String> updatedJobs = new ArrayList<String>();
    ArrayList<String> newJobs = new ArrayList<String>();
    ArrayList<String> deletedJobs = new ArrayList<String>();

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (receivedJobNames.contains(line)) {
            updatedJobs.add(line);/*w w w. ja va 2s. c om*/
            receivedJobNames.remove(line);
        } else {
            deletedJobs.add(line);
        }
    }
    logger.info("There are " + receivedJobNames.size() + " new jobs");
    logger.info("There are " + deletedJobs.size() + " deleted jobs");
    logger.info("There are " + updatedJobs.size() + " updated jobs");
    for (String s : receivedJobNames) {
        newJobs.add(s);
    }

    scanner.close();
    FileWriter writer = new FileWriter(projectFile, false);
    for (String s : updatedJobs) {
        writer.write(s);
        writer.write("\n");
    }
    for (String s : newJobs) {
        writer.write(s);
        writer.write("\n");
    }
    writer.close();
    return deletedJobs;
}

From source file:data_gen.Data_gen.java

public static String get_config_Dir() {
    Scanner s = new Scanner(System.in);
    System.out.println("\n" + "Enter the name or Directory of the configration file to be used: " + "\n");
    String Dir = s.nextLine().trim();
    return Dir;//from   ww w. j  a va 2 s .com
}

From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java

/**
 * Reads settings (keywords / urls / serach terms) line-by-line from a file.
 *
 * @param fileName the name of the file to read from
 * @return a {@link List} of strings line-by-line
 * @throws KeywordOptimizerException in case there is a problem reading the file
 *///from   w w  w.  jav  a2  s  . c o  m
private static List<String> loadFromFile(String fileName) throws KeywordOptimizerException {
    List<String> out = new ArrayList<String>();

    Scanner scan = null;
    try {
        scan = new Scanner(new File(fileName));
        while (scan.hasNextLine()) {
            String line = scan.nextLine().trim();

            // Ignore comment lines.
            if (line.startsWith("#")) {
                continue;
            }

            out.add(line);
        }
        return out;
    } catch (IOException e) {
        throw new KeywordOptimizerException("Error loading file '" + fileName + "'", e);
    } finally {
        if (scan != null) {
            scan.close();
        }
    }
}

From source file:clummy.classes.DataHandlingClass.java

/**
 * to read file by line and pass each line to arraylist
 * only read starting at the third line//ww w  .  ja v a2s  . c  om
 * @param fileName String
 * @return ArrayList
 */
public static ArrayList<String> readFile(String fileName) {
    ArrayList<String> readList = new ArrayList<>();

    Scanner scan;
    try {
        scan = new Scanner(new FileReader(fileName));
        int lineCount = 0;
        while (scan.hasNextLine()) {
            lineCount++;
            if (lineCount <= 3)
                scan.nextLine();
            if (lineCount >= 4)
                readList.add(scan.nextLine());
        }
        scan.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
    }
    return readList;
}

From source file:dsfixgui.FileIO.DSFixFileController.java

/**
 *Writes a string to a text file/*from   w  ww .  j  av  a  2s  . c  o  m*/
 * 
 * @param filePath
 *  the path of the file to be read, including the filename
 * @param text
 *  the String to be written to the file; can be more than one line.
 * @param overwrite
 *  determines whether the user wants to overwrite the write file if it
 *  already exists. If true, pre-existing file will be overwritten
 * @throws IIOException
 *  if the write file already exists and the user allowed overwriting, but
 *  the file could not be overwritten
 * @throws AccessDeniedException
 *  if the write file already exists but the user didn't allow overwriting
 * @throws IOException
 *  if an error occurs initializing the BufferedWriter
 */
public static void writeTextFile(String filePath, String text, boolean overwrite)
        throws IIOException, IOException, AccessDeniedException {

    //The file to be written
    File writeFile = new File(filePath);
    if (writeFile.exists() && overwrite) {
        //If file exists, try to delete it
        if (!writeFile.delete()) {
            //If file cannot be deleted, throw OIOException
            throw new IIOException("Could not delete pre-existing file: " + filePath);
        }
    } else if (writeFile.exists() && !overwrite) {
        //If file exists but is not allowed to be overwritten, throw AccessDeniedException
        throw new AccessDeniedException(writeFile.getPath());
    }

    //Format each linebreak to be displayed correctly in a text file
    String formattedText = text.replaceAll("\n", String.format("%n"));
    //Initialize BufferedWriter to write string to file
    BufferedWriter fileWriter = new BufferedWriter(new FileWriter(writeFile));
    //Write the file
    Scanner scanner = new Scanner(formattedText);
    while (scanner.hasNextLine()) {
        fileWriter.write(scanner.nextLine());
        fileWriter.newLine();
    }

    fileWriter.close();
}

From source file:com.cisco.dbds.utils.tims.TIMS.java

/**
 * Readhtmlfile pass.//from  w w  w  . jav  a2  s .c o m
 *
 * @return the array list
 * @throws FileNotFoundException the file not found exception
 */
public static ArrayList<String> readhtmlfilePass() throws FileNotFoundException {
    ArrayList<String> re = new ArrayList<String>();

    String fEncoding = "UTF-8";
    String tt = "";
    int fcount = 0;
    Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
    try {
        while (scanner.hasNextLine()) {

            tt = scanner.nextLine();
            tt = tt.trim();

            if (tt.contains("Failed Test Case ID"))
                fcount = 1;

            if (fcount == 0 && tt.contains("Ttv") && !(tt.contains("Precheck"))
                    && !(tt.contains("Precondition"))) {
                System.out.println("LINE read: " + tt);

                String a[] = tt.split("<td>");
                System.out.println("tcid: " + a[3].substring(a[3].indexOf('T'), 19));
                System.out.println("Desc: " + a[5].substring(0, a[5].indexOf("<")));
                System.out.println("status: " + a[6].substring(a[6].indexOf(">") + 1, a[6].indexOf("d") + 1));

                String aa = a[3].substring(a[3].indexOf('T'), 19) + "~" + a[5].substring(0, a[5].indexOf("<"))
                        + "~" + a[6].substring(a[6].indexOf(">") + 1, a[6].indexOf("d") + 1);
                re.add(aa);

            }

        }

    } finally {
        scanner.close();
    }
    return re;

}