Example usage for java.util Scanner close

List of usage examples for java.util Scanner close

Introduction

In this page you can find the example usage for java.util Scanner close.

Prototype

public void close() 

Source Link

Document

Closes this scanner.

Usage

From source file:example.store.StoreInitializer.java

/**
 * Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to
 * persisted./*from   www .ja  v a  2  s .co  m*/
 *
 * @return
 * @throws Exception
 */
public static List<Store> readStores() throws Exception {

    ClassPathResource resource = new ClassPathResource("starbucks.csv");
    Scanner scanner = new Scanner(resource.getInputStream());
    String line = scanner.nextLine();
    scanner.close();

    FlatFileItemReader<Store> itemReader = new FlatFileItemReader<Store>();
    itemReader.setResource(resource);

    // DelimitedLineTokenizer defaults to comma as its delimiter
    DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
    tokenizer.setNames(line.split(","));
    tokenizer.setStrict(false);

    DefaultLineMapper<Store> lineMapper = new DefaultLineMapper<Store>();
    lineMapper.setLineTokenizer(tokenizer);
    lineMapper.setFieldSetMapper(StoreFieldSetMapper.INSTANCE);
    itemReader.setLineMapper(lineMapper);
    itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
    itemReader.setLinesToSkip(1);
    itemReader.open(new ExecutionContext());

    List<Store> stores = new ArrayList<>();
    Store store = null;

    do {

        store = itemReader.read();

        if (store != null) {
            stores.add(store);
        }

    } while (store != null);

    return stores;
}

From source file:eu.databata.engine.util.PropagatorTableExport.java

private static String askDelimiter() {
    System.out.println("Insert data delimiter [|]:");
    Scanner delimiterInput = new Scanner(System.in);
    String delimiter = delimiterInput.nextLine();
    if (StringUtils.isEmpty(delimiter)) {
        delimiter = "|";
    }/* ww w.  j  a va2 s.co m*/
    delimiterInput.close();
    return delimiter;
}

From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java

private static String readFromFile(File file) throws IOException {
    StringBuilder buf = new StringBuilder();
    Scanner scan = new Scanner(new FileInputStream(file));
    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        buf.append(line);//from www .  j  a va  2s  . co m
        buf.append("\n");
    }
    scan.close();
    return buf.toString();
}

From source file:game.utils.Utils.java

public static String readFile(File file) {
    String ret = null;//from w w  w.  ja va  2  s .  c  o  m
    try {
        Scanner scanner = new Scanner(file);
        ret = scanner.useDelimiter("\\Z").next();
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java

public static void upload(String url, String playerName, File jsonfile, File sourcefile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   www.ja va  2  s. co  m*/
        HttpPost httppost = new HttpPost(url);

        FileBody json = new FileBody(jsonfile);
        FileBody source = new FileBody(sourcefile);
        String jsontext = readFromFile(jsonfile);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN))
                .addPart("jsonfile", json).addPart("sourcefile", source)
                .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN))
                .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext",
                        new StringBody("public class Foo {\n  int x=5\n}", ContentType.TEXT_PLAIN))
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            //System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                //System.out.println("Response content length: " + resEntity.getContentLength());
                Scanner sc = new Scanner(resEntity.getContent());
                while (sc.hasNext()) {
                    System.out.println(sc.nextLine());
                }
                sc.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:example.UserInitializer.java

private static List<User> readUsers(Resource resource) throws Exception {

    Scanner scanner = new Scanner(resource.getInputStream());
    String line = scanner.nextLine();
    scanner.close();

    FlatFileItemReader<User> reader = new FlatFileItemReader<User>();
    reader.setResource(resource);//from   w w w  .  ja v  a 2 s  .  c  o  m

    DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
    tokenizer.setNames(line.split(","));
    tokenizer.setStrict(false);

    DefaultLineMapper<User> lineMapper = new DefaultLineMapper<User>();
    lineMapper.setFieldSetMapper(fields -> {

        User user = new User();

        user.setEmail(fields.readString("email"));
        user.setFirstname(capitalize(fields.readString("first")));
        user.setLastname(capitalize(fields.readString("last")));
        user.setNationality(fields.readString("nationality"));

        String city = Arrays.stream(fields.readString("city").split(" "))//
                .map(StringUtils::capitalize)//
                .collect(Collectors.joining(" "));
        String street = Arrays.stream(fields.readString("street").split(" "))//
                .map(StringUtils::capitalize)//
                .collect(Collectors.joining(" "));

        try {
            user.setAddress(new Address(city, street, fields.readString("zip")));
        } catch (IllegalArgumentException e) {
            user.setAddress(new Address(city, street, fields.readString("postcode")));
        }

        user.setPicture(new Picture(fields.readString("large"), fields.readString("medium"),
                fields.readString("thumbnail")));
        user.setUsername(fields.readString("username"));
        user.setPassword(fields.readString("password"));

        return user;
    });

    lineMapper.setLineTokenizer(tokenizer);

    reader.setLineMapper(lineMapper);
    reader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy());
    reader.setLinesToSkip(1);
    reader.open(new ExecutionContext());

    List<User> users = new ArrayList<>();
    User user = null;

    do {

        user = reader.read();

        if (user != null) {
            users.add(user);
        }

    } while (user != null);

    return users;
}

From source file:com.microsoft.azure.storage.util.KeyVaultUtility.java

/**
 * Creates a secret in Azure Key Vault and returns its ID.
 * /*  ww w .j  a  va2s  .co  m*/
 * @param secretName
 *            The name of the secret to create
 * @return The ID of the created secret
 * @throws InterruptedException
 * @throws ExecutionException
 * @throws NoSuchAlgorithmException
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public static String SetUpKeyVaultSecret(String secretName) throws InterruptedException, ExecutionException,
        NoSuchAlgorithmException, URISyntaxException, MalformedURLException {
    KeyVaultClient cloudVault = GetKeyVaultClient();

    if (Utility.vaultURL == null || Utility.vaultURL.isEmpty()) {
        throw new IllegalArgumentException("No Keyvault URL specified.");
    }

    try {
        // Delete the secret if it exists.
        cloudVault.deleteSecretAsync(Utility.vaultURL, secretName).get();
    } catch (ExecutionException ex) {
        boolean keyNotFound = false;
        if (ex.getCause().getClass() == ServiceException.class) {
            ServiceException serviceException = (ServiceException) ex.getCause();
            if (serviceException.getHttpStatusCode() == 404) {
                keyNotFound = true;
            }
        }

        if (!keyNotFound) {
            System.out.println(
                    "Unable to access the specified vault. Please confirm the KVClientId, KVClientKey, and VaultUri are valid in the app.config file.");
            System.out.println(
                    "Also ensure that the client ID has previously been granted full permissions for Key Vault secrets using the Set-AzureKeyVaultAccessPolicy command with the -PermissionsToSecrets parameter.");
            System.out.println("Press any key to exit");
            Scanner input = new Scanner(System.in);
            input.nextLine();
            input.close();
            throw ex;
        }
    }

    // Create a 256bit symmetric key and convert it to Base64.
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256); // Note that we cannot use SymmetricKey.KeySize256,
                      // because this resolves to '0x20'.
    SecretKey wrapKey = keyGen.generateKey();

    // Store the Base64 of the key in the key vault. Note that the
    // content-type of the secret must
    // be application/octet-stream or the KeyVaultKeyResolver will not load
    // it as a key.
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/octet-stream");
    Secret cloudSecret = cloudVault.setSecretAsync(Utility.vaultURL, secretName,
            Base64.encodeBase64String(wrapKey.getEncoded()), "application/octet-stream", null, null).get();

    // Return the base identifier of the secret. This will be resolved to
    // the current version of the secret.
    return cloudSecret.getSecretIdentifier().getBaseIdentifier();
}

From source file:Main.java

/**
 * read one file and return its content as string
 * @param fileName/* w  ww .  j  ava 2  s.co  m*/
 * @return
 * @throws FileNotFoundException
 */
public static String readFileToString(String fileName) throws FileNotFoundException {
    File file = new File(fileName);
    if (file.exists()) {
        StringBuilder stringBuilder = new StringBuilder((int) file.length());
        Scanner scanner = new Scanner(file, "UTF-8");
        String lineSeparator = System.getProperty("line.separator");

        while (scanner.hasNextLine()) {
            stringBuilder.append(scanner.nextLine() + lineSeparator);
        }

        scanner.close();
        return stringBuilder.toString();
    }

    Log.e(TAG_CLASS, "no file called: " + fileName);
    return null;
}

From source file:Main.java

private static StringReader fromStreamToStringReader(InputStream inputStream, String encoding) {
    StringBuilder content = new StringBuilder();

    Scanner scanner = null;
    try {/*from   w  w w  . ja  va  2 s  . c om*/
        scanner = new Scanner(inputStream, encoding);

        while (scanner.hasNextLine()) {
            content.append(scanner.nextLine()).append("\n");
        }
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }

    return new StringReader(content.toString());
}

From source file:com.adyen.httpclient.HttpURLConnectionClient.java

private static String getResponseBody(InputStream responseStream) throws IOException {
    //\A is the beginning of the stream boundary
    Scanner scanner = new Scanner(responseStream, CHARSET);
    String rBody = scanner.useDelimiter("\\A").next();
    scanner.close();
    responseStream.close();//from   www  .  jav a 2s .co m
    return rBody;
}