Java Path File Read nio readIntsFromFile(String filePath)

Here you can find the source of readIntsFromFile(String filePath)

Description

Reads a file which has one integer value on each line, and returns the values in an integer array.

License

Open Source License

Parameter

Parameter Description
filePath the path of the file to read

Return

int array containing the values from each line

Declaration

public static int[] readIntsFromFile(String filePath) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Main {
    /**//  w  ww.j  a v  a 2s  . c  o  m
     * Reads a file which has one integer value on each line, and returns the values
     * in an integer array.
     * 
     * @param filePath the path of the file to read
     * @return int array containing the values from each line
     */
    public static int[] readIntsFromFile(String filePath) {
        try {
            Path path = Paths.get(filePath);
            List<Integer> values = new ArrayList<Integer>();

            // Read values from file at given file path.
            BufferedReader reader = Files.newBufferedReader(path,
                    Charset.defaultCharset());
            String line = reader.readLine();
            while (line != null) {
                Integer value = Integer.valueOf(line);
                values.add(value);
                line = reader.readLine();
            }

            // Convert List<Integer> to int[].
            int[] intArray = new int[values.size()];
            int i = 0;
            for (Integer value : values) {
                intArray[i++] = value.intValue();
            }

            // Return the int[].
            return intArray;

        } catch (IOException e) {
            System.out.println("Caught IOException: " + e
                    + "\nReturning null");
            return null;
        }
    }
}

Related

  1. readFileToString(@Nonnull Path file)
  2. readFromFile(Path absolutePath)
  3. readFromFile(String path)
  4. readFromFile(String path)
  5. readFully(Path filePath)
  6. readJson(Class dataClass, Path path)
  7. readJsonObject(Path path, TypeReference typeReference)
  8. readKeyFile(String path)
  9. readLine(BufferedReader br, Path path)