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:com.pdemartino.test.springctxs.App.java

private static String askForContextFile() {
    String springType;/*from www .  ja  v a 2s .c  o  m*/

    // define prompt string
    String promptString = "";
    for (Map.Entry<String, Context> ctx : contexts.entrySet()) {
        promptString += "\n" + ctx.getKey() + ": " + ctx.getValue().description;
    }

    // User Input
    Scanner scanIn = new Scanner(System.in);
    do {
        System.out.println("Choose configuration type:" + promptString);
        springType = scanIn.nextLine().trim();
    } while (!contexts.containsKey(springType));

    return contexts.get(springType).contextFile;
}

From source file:fi.jyu.it.ties456.week38.Main.Main.java

public static void createCourse(TeacherRegistry teacher, CourseIS course)
        throws NoSuchTeacherException_Exception {
    Scanner inputID = new Scanner(System.in);
    Scanner cinName = new Scanner(System.in);
    Scanner cinID = new Scanner(System.in);
    Scanner cinCredit = new Scanner(System.in);
    Scanner cinDP = new Scanner(System.in);
    System.out.println("Course Name");
    String cName = cinName.nextLine();
    System.out.println("Search Teacher ID");
    String SID = cinID.nextLine();
    System.out.println(teacher.searchForPerson(SID).get(0).getID());
    System.out.println("Input Teacher ID");
    String ID = inputID.nextLine();
    System.out.println("Course Credit");
    int credit = 0;
    try {/*from  w w w. j a  v a  2  s.  c  om*/
        credit = cinCredit.nextInt();
    } catch (InputMismatchException e) {
        System.err.println("Course credit must be an int");
        main(null);
    }
    System.out.println("Course Description");
    String description = cinDP.nextLine();
    System.out.println(course.createCourse(cName, ID, credit, description));
}

From source file:edu.harvard.hul.ois.fits.junit.VideoStdSchemaTestXmlUnit.java

@Test
public void testVideoXmlUnitFitsOutput_AVC() throws Exception {

    Fits fits = new Fits();

    // First generate the FITS output
    File input = new File("testfiles/FITS-SAMPLE-44_1_1_4_4_4_6_1_1_2_3_1.mp4");
    FitsOutput fitsOut = fits.examine(input);

    XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
    String actualXmlStr = serializer.outputString(fitsOut.getFitsXml());

    // Read in the expected XML file
    Scanner scan = new Scanner(new File("testfiles/output/FITS-SAMPLE-44_1_1_4_4_4_6_1_1_2_3_1_mp4_FITS.xml"));
    String expectedXmlStr = scan.useDelimiter("\\Z").next();
    scan.close();//from   ww  w.ja va 2  s  . co m

    // Set up XMLUnit
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalizeWhitespace(true);

    Diff diff = new Diff(expectedXmlStr, actualXmlStr);

    // Initialize attributes or elements to ignore for difference checking
    diff.overrideDifferenceListener(new IgnoreNamedElementsDifferenceListener("version", "toolversion",
            "dateModified", "fslastmodified", "startDate", "startTime", "timestamp", "fitsExecutionTime",
            "executionTime", "filepath", "location"));

    DetailedDiff detailedDiff = new DetailedDiff(diff);

    // Display any Differences
    List<Difference> diffs = detailedDiff.getAllDifferences();
    if (!diff.identical()) {
        StringBuffer differenceDescription = new StringBuffer();
        differenceDescription.append(diffs.size()).append(" differences");

        System.out.println(differenceDescription.toString());
        for (Difference difference : diffs) {
            System.out.println(difference.toString());
        }

    }

    assertTrue("Differences in XML", diff.identical());
}

From source file:PostTest.java

/**
 * Makes a POST request and returns the server response.
 * @param urlString the URL to post to/*w ww .j  a va2 s  .co  m*/
 * @param nameValuePairs a map of name/value pairs to supply in the request.
 * @return the server reply (either from the input stream or the error stream)
 */
public static String doPost(String urlString, Map<String, String> nameValuePairs) throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
        if (first)
            first = false;
        else
            out.print('&');
        String name = pair.getKey();
        String value = pair.getValue();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
        in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
        if (!(connection instanceof HttpURLConnection))
            throw e;
        InputStream err = ((HttpURLConnection) connection).getErrorStream();
        if (err == null)
            throw e;
        in = new Scanner(err);
    }

    while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
    }

    in.close();
    return response.toString();
}

From source file:com.alibaba.openapi.client.util.URLEncodedUtils.java

/**
 * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an
 * {@link HttpEntity}. The encoding is taken from the entity's
 * Content-Encoding header./*  www. j  av  a 2 s .  com*/
 * <p>
 * This is typically used while parsing an HTTP POST.
 * 
 * @param entity
 *            The entity to parse
 * @throws IOException
 *             If there was an exception getting the entity's data.
 */
public static List<NameValuePair> parse(final HttpEntity entity) throws IOException {
    List<NameValuePair> result = Collections.emptyList();
    if (isEncoded(entity)) {
        final String content = EntityUtils.toString(entity);
        final Header encoding = entity.getContentEncoding();
        if (content != null && content.length() > 0) {
            result = new ArrayList<NameValuePair>();
            parse(result, new Scanner(content), encoding != null ? encoding.getValue() : null);
        }
    }
    return result;
}

From source file:ThreadedEchoServer.java

public void run() {
    try {/* w  w w . j a va2  s .com*/
        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:org.eclipse.lyo.testsuite.server.trsutils.TestCore.java

/**
 * This method is used to read the contents
 * of a file as a String//from  w w  w .java2  s .c  om
 * @param f
 * @return
 */
protected static String readFileAsString(File f) {

    StringBuilder stringBuilder = new StringBuilder();
    Scanner scanner = null;
    try {
        scanner = new Scanner(f);
    } catch (FileNotFoundException e) {
        return null;
    }

    try {
        while (scanner.hasNextLine()) {
            stringBuilder.append(scanner.nextLine() + "\n");
        }
    } finally {
        scanner.close();
    }
    return stringBuilder.toString();
}

From source file:formatMessage.VerifyInputScanner.java

/**
 * Ga naar https://commons.apache.org/proper/commons-validator/download_validator.cgi
 *         download de bin file//  w  ww  .ja v a 2s  .c  om
 * Ga naar libraries in netbeans rechtermuisknop workshop1 properties
 * Druk op libraries
 * add library
 * create
 * dan add the file commons-validator-1.5.0 aan de classpath
 * 
 * @return 
 */
public static String verifyEmail() {
    Scanner input = new Scanner(System.in);

    while (true) {
        try {

            String verified = input.next();
            EmailValidator emailVal = EmailValidator.getInstance();
            if (emailVal.isValid(verified)) {

                return verified;
            }
        } catch (InputMismatchException e) {
            System.out.println("Geen juiste invoer probeer opnieuw");

        }
    }

}

From source file:com.threewks.thundr.configuration.PropertiesLoader.java

private Map<String, String> readProperties(String resourceAsString) {
    Map<String, String> properties = new LinkedHashMap<String, String>();
    Scanner scanner = new Scanner(resourceAsString);
    try {/*from w ww  .  ja  v a  2s  .c o m*/
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            line = StringUtils.substringBefore(line, "#");
            line = StringUtils.trimToNull(line);
            String key = StringUtils.substringBefore(line, "=");
            String value = StringUtils.substringAfter(line, "=");
            if (key != null) {
                properties.put(key, value);
            }
        }
    } finally {
        scanner.close();
    }
    return properties;
}

From source file:com.deployd.Deployd.java

public static JSONObject post(JSONObject input, String uri)
        throws ClientProtocolException, IOException, JSONException {

    HttpPost post = new HttpPost(endpoint + uri);
    HttpClient client = new DefaultHttpClient();
    post.setEntity(new ByteArrayEntity(input.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(post);
    ByteArrayEntity e = (ByteArrayEntity) response.getEntity();
    InputStream is = e.getContent();
    String data = new Scanner(is).next();
    JSONObject result = new JSONObject(data);
    return result;
}