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:example.store.StoreInitializer.java

/**
 * Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to
 * persisted./* www .j a  v a2  s . c  o 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:SystemTrayTest.java

private static List<String> readFortunes() {
    List<String> fortunes = new ArrayList<String>();
    try {//from  w  w w .j a v a2  s  . c o m
        Scanner in = new Scanner(new File("fortunes"));
        StringBuilder fortune = new StringBuilder();
        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (line.equals("%")) {
                fortunes.add(fortune.toString());
                fortune = new StringBuilder();
            } else {
                fortune.append(line);
                fortune.append(' ');
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return fortunes;
}

From source file:com.thalesgroup.sonar.plugins.tusar.utils.Utils.java

private static void scanIniContent(Scanner scanner, List<String[]> metrics) {
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (!line.startsWith(Constants.COMMENTS)) {
            String[] tokens = line.split(Constants.CSV_SEPARATOR);
            if (tokens.length >= Constants.TOKENS_LENGTH) {
                metrics.add(tokens);/*w  w w  .  j ava2  s  .  c  om*/
            } else {
                logger.warn(line + " contains less than three elements");
            }
        }
    }
}

From source file:Main.java

public static Map<String, List<String>> createDictionary(Context context) {
    try {/*from  w w w  .  java  2 s .c  om*/
        AssetManager am = context.getAssets();
        InputStream is = am.open(DICTIONARY_FILENAME);
        Scanner reader = new Scanner(is);
        Map<String, List<String>> map = new HashMap<String, List<String>>();

        while (reader.hasNextLine()) {
            String word = reader.nextLine();
            char[] keyArr = word.toCharArray();
            Arrays.sort(keyArr);
            String key = String.copyValueOf(keyArr);

            List<String> wordList = map.get(key);
            if (wordList == null) {
                wordList = new LinkedList<String>();
            }
            wordList.add(word);
            map.put(key, wordList);
        }
        reader.close();
        return map;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    return null;
}

From source file:azureml_besapp.AzureML_BESApp.java

/**
 * Read the API key and API URL of Azure ML request response REST API
 * /*from  w  w w .  j a va  2s  . co  m*/
 * @param filename fully qualified file name that contains API key and API URL
 */
public static void readApiInfo(String filename) {

    try {
        File apiFile = new File(filename);
        Scanner sc = new Scanner(apiFile);

        apiurl = sc.nextLine();
        apikey = sc.nextLine();
        startJobUrl = sc.nextLine();

    } catch (Exception e) {
        System.out.println(e.toString());
    }

}

From source file:jmap2gml.ItemImage.java

private static HashMap<String, Image> readConfig() {
    HashMap<String, Image> out = new HashMap<>();
    JSONTEXT = "";
    Image img;/*from   w  w w .j  a v  a 2s  . c  o m*/

    Scanner scan;
    try {
        scan = new Scanner(new File("ImageItemConfig"));

        while (scan.hasNext()) {
            JSONTEXT += scan.nextLine();
        }

        config = new JSONObject(JSONTEXT);

        for (String str : config.keySet()) {
            if (!str.contains("XOFFSET") && !str.contains("YOFFSET")) {
                img = (new ImageIcon(config.getString(str))).getImage();
                out.put(str, img);
            }
        }
    } catch (Exception ex) {
        Logger.getLogger(ItemImage.class.getName()).log(Level.SEVERE, null, ex);
    }

    return out;
}

From source file:de.ifgi.mosia.wpswfs.Util.java

public static Set<String> readConfigFilePerLine(String resourcePath) throws IOException {
    URL resURL = Util.class.getResource(resourcePath);
    URLConnection resConn = resURL.openConnection();
    resConn.setUseCaches(false);/*from   w ww  .ja v  a 2s  . c o m*/
    InputStream contents = resConn.getInputStream();

    Scanner sc = new Scanner(contents);
    Set<String> result = new HashSet<String>();
    String line;
    while (sc.hasNext()) {
        line = sc.nextLine();
        if (line != null && !line.isEmpty() && !line.startsWith("#")) {
            result.add(line.trim());
        }
    }
    sc.close();

    return result;
}

From source file:Main.java

/**
 * read one file and return its content as string
 * @param fileName//w  ww  .j av  a  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:com.noisepages.nettoyeur.usb.DeviceInfo.java

private static String getName(String url) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    Scanner scanner = new Scanner(response.getEntity().getContent());
    while (scanner.hasNext()) {
        String line = scanner.nextLine();
        int start = line.indexOf("Name:") + 6;
        if (start > 5) {
            int end = line.indexOf("<", start);
            if (end > start) {
                return line.substring(start, end);
            }/*from   w w  w.j a v  a  2s . co m*/
        }
    }
    return null;
}

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

/**
 * Creates a secret in Azure Key Vault and returns its ID.
 * //w  w  w.  j  a va  2 s .c o  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();
}