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:de.tudarmstadt.ukp.dkpro.tc.crfsuite.task.CRFSuiteTestTask.java

private static String captureProcessOutput(Process aProcess) {
    InputStream src = aProcess.getInputStream();
    Scanner sc = new Scanner(src);
    StringBuilder dest = new StringBuilder();
    while (sc.hasNextLine()) {
        String l = sc.nextLine();
        dest.append(l + "\n");
    }/*from   ww  w .java 2  s .  c  o m*/
    sc.close();
    return dest.toString();
}

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

/**
 * Reads and parses the confirmation of the user for an action.
 *
 * @return <code>true</code> if the user confirmed with Y for YES, <code>false</code> otherwise.
 */// w w w .jav  a2  s  . c  o m
public static boolean readAndParseUserConfirmation() {
    LOG.info("Confirm please: [Y] or [N]");
    boolean validChoice = false;
    boolean choice = false;

    Scanner scanner = new Scanner(System.in);
    while (!validChoice) {
        String line = scanner.nextLine();
        if (StringUtils.deleteWhitespace(line).equalsIgnoreCase("Y")) {
            choice = true;
            validChoice = true;
        } else if (StringUtils.deleteWhitespace(line).equalsIgnoreCase("N")) {
            choice = false;
            validChoice = true;
        } else {
            LOG.error("Invalid choice. Try again!");
        }
    }

    return choice;
}

From source file:cpd3314.buildit12.CPD3314BuildIt12.java

/**
 * Build a sample method that saves a handful of car instances as Serialized
 * objects, and as JSON objects, then re-open the saved versions in a
 * different method//from  www.jav a 2  s .c  o m
 */
public static void doBuildIt2Input() {
    // Unserialize the Objects -- Save them to an ArrayList and Output
    try {
        FileInputStream objFile = new FileInputStream("cars.obj");
        ObjectInputStream objStream = new ObjectInputStream(objFile);

        ArrayList<Car> cars = new ArrayList<>();

        boolean eof = false;
        while (!eof) {
            try {
                cars.add((Car) objStream.readObject());
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
            } catch (EOFException ex) {
                // We must catch the EOF exception to leave the loop
                eof = true;
            }
        }

        System.out.println("Unserialized Data:");
        for (Car car : cars) {
            System.out.printf("Make: %s, Model: %s, Year: %d\n", car.getMake(), car.getModel(), car.getYear());
        }
    } catch (IOException ex) {
        Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Read from JSON and Output
    try {
        File file = new File("cars.json");
        Scanner input = new Scanner(file);
        while (input.hasNext()) {
            JSONParser parse = new JSONParser();
            try {
                // This should be the root JSON Object, which has an array of Car objects
                JSONObject json = (JSONObject) parse.parse(input.nextLine());

                // We pull the array out to work with it
                JSONArray cars = (JSONArray) json.get("cars");

                System.out.println("Un-JSON-ed Data:");
                for (Object car : cars) {
                    // Convert each Object to a JSONObject
                    JSONObject carJSON = (JSONObject) car;
                    // Convert each JSONObject to an actual Car
                    Car carObj = new Car(carJSON);
                    // Output from the Actual Car class                        
                    System.out.printf("Make: %s, Model: %s, Year: %d\n", carObj.getMake(), carObj.getModel(),
                            carObj.getYear());
                }
            } catch (ParseException ex) {
                Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(CPD3314BuildIt12.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:dm_p2.DBSCAN.java

public static void generateLinkedHashMap(String filename) {
    String filePath = new File("").getAbsolutePath();

    try {//w  w w .j a v  a 2 s. co m
        Scanner s = new Scanner(new File(filePath + "/src/dm_p2/" + filename));
        while (s.hasNext()) {
            String inputLine = s.nextLine();
            String[] splitData = inputLine.split("\t");
            int geneId = Integer.parseInt(splitData[0]);
            expressionValues = new ArrayList<Double>();
            int cc = Integer.parseInt(splitData[1]);
            given.put(geneId, cc);
            for (int i = 2; i < splitData.length; i++) {

                expressionValues.add(Double.parseDouble(splitData[i]));
            }
            //                gene g=new gene();
            //                g.add(geneId, expressionValues);
            //                genelist.add(g);
            linkedHashMap.put(geneId, expressionValues);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

From source file:com.amazonaws.services.dynamodbv2.online.index.ViolationDetector.java

private static boolean getUseConditionalUpdateOptionFromConsole() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Do you want to use conditional update? y/n ");
    String op = scanner.nextLine().trim();
    if (op.equalsIgnoreCase("n")) {
        logger.info("User decided to NOT use conditional update. Will use normal update.");
        scanner.close();/* ww  w  . jav a2s  . co m*/
        return false;
    } else if (op.equalsIgnoreCase("y")) {
        logger.info("User decided to use conditional update.");
        scanner.close();
        return true;
    } else {
        logger.error("Invalid entry by the user. Will exit.");
        System.out.println("Please type in y/n, exiting...");
        scanner.close();
        System.exit(0);
    }
    return false;
}

From source file:com.google.api.ads.adwords.awreporting.server.AwReportingServer.java

/**
 * Prints the sample properties file on the default output.
 *///from   w w w .ja va2 s .  c  om
private static void printSamplePropertiesFile() {

    System.out.println("\n  File: aw-reporting-server-sample.properties example");

    ClassPathResource sampleFile = new ClassPathResource(DAFAULT_PROPERTIES_LOCATION);
    Scanner fileScanner = null;
    try {
        fileScanner = new Scanner(sampleFile.getInputStream());
        while (fileScanner.hasNext()) {
            System.out.println(fileScanner.nextLine());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fileScanner != null) {
            fileScanner.close();
        }
    }
}

From source file:com.amazonaws.services.dynamodbv2.online.index.ViolationDetector.java

private static void confirmDelete() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Are you sure to delete all violations on the table? y/n ");
    String op = scanner.nextLine().trim();
    if (op.equalsIgnoreCase("n")) {
        logger.info("User decided to not delete. Exiting...");
        scanner.close();/*from   w  w  w .j a  va  2 s .c  o  m*/
        System.exit(0);
    } else if (op.equalsIgnoreCase("y")) {
        logger.info("Confirmed deletion. Will delete all violations in the table...");
        scanner.close();
    } else {
        logger.error("Invalid entry by the user. Will exit.");
        System.out.println("Please type in y/n, exiting...");
        scanner.close();
        System.exit(0);
    }
}

From source file:com.zimbra.cs.mailbox.util.MetadataDump.java

private static String loadFromFile(File file) throws ServiceException {
    try {//from ww  w .  j a  v a  2 s .  co m
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            Scanner scan = new Scanner(fis);
            StringBuilder builder = new StringBuilder();
            while (scan.hasNextLine()) {
                builder.append(scan.nextLine());
            }
            return builder.toString();
        } finally {
            if (fis != null)
                fis.close();
        }
    } catch (IOException e) {
        throw ServiceException.FAILURE("IOException while reading from " + file.getAbsolutePath(), e);
    }
}

From source file:edu.cmu.cs.lti.ark.fn.parsing.DataPrep.java

public static Map<String, Integer> readFeatureIndex(File alphabetFile) throws FileNotFoundException {
    HashMap<String, Integer> featureIndex = Maps.newHashMap();
    final FileInputStream inputStream = new FileInputStream(alphabetFile);
    Scanner scanner = new Scanner(inputStream);
    try {//w w  w. j  a va 2 s .com
        // skip the first line
        scanner.nextLine();
        int count = 0;
        while (scanner.hasNextLine()) {
            addFeature(scanner.nextLine(), featureIndex);
            if (count % 100000 == 0) {
                System.err.print(count + " ");
            }
            count++;
        }
        System.err.println();
    } finally {
        closeQuietly(inputStream);
    }
    return featureIndex;
}

From source file:magixcel.Main.java

private static void setup() {
    Scanner s = new Scanner(System.in);
    boolean doContinue = false;

    //        Intro
    printLogo();// w  w w  . j a va 2 s .  c om
    System.out.println("Welcome to MagiXcel");
    System.out.println("Current encoding is " + Charset.defaultCharset());

    //        Table name
    while (!doContinue) {
        System.out.println("Type your desired table name:");
        if (s.hasNextLine()) {
            Table.setTableName(s.nextLine());
        }

        doContinue = isThisOk(s);
    }
    doContinue = false;

    //        File path
    String path = "";
    while (!doContinue) {
        System.out.println("Enter FULL path of .csv or .txt file you wish to convert");
        if (s.hasNextLine()) {
            path = StringEscapeUtils.escapeJava(s.nextLine());
        }
        FileMan.setPath(path);
        if (FileMan.currentPathIsValid()) {
            doContinue = isThisOk(s);
        } else {
            System.out.println("ERROR: Invalid Path");
            doContinue = false;
        }

    }
    doContinue = false;

    //        File setup
    FileMan.getLinesFromFile();
    Table.setColumnNames(FileMan.takeFirstRow());
    FileMan.addRowsToTable();

    //        Choose output mode
    System.out.println("Choose output mode:");
    OutputFormat.printOutputOptionsNumbered();
    int selectedOption = -1;
    while (!doContinue) {
        if (s.hasNextLine()) {
            selectedOption = Integer.parseInt(s.nextLine());
        }
        doContinue = OutputFormat.chooseOption(selectedOption, s);
    }

    doContinue = false;
    OutputFormat.format();

    FileMan.writeToFile();

    System.out.println("Thank you for using MagiXcel!");
    System.out.println("Press Enter to exit");
    s.nextLine();
    s.close();

}