How to read from a text file and store into an array in java

Store shah :

How can I read from a text file that contains a lot of numbers and store it into an int array and at the end I would pass that array and size of the array to my other method which will be used in my application. So far my code reads from a text file and stores it into an ArrayList, not an array. Thank you.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.Buffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;

    public class Test {

        static int i =0;
        public static void main(String args[]) throws URISyntaxException {
            try {
        URL path = ClassLoader.getSystemResource("input.txt");

            if ( path== null) {
                System.out.println("File is not avilable!");
            }

                File myfile= new File(path.toURI());
                //BufferedReader reader = new BufferedReader (new FileReader(myfile));
                Scanner myscan = new Scanner (myfile);

            ArrayList<Integer> input = new ArrayList<Integer>();
                while (myscan.hasNextLine()) {

                input.add(myscan.nextInt());
                }
                int size = input.size();
                System.out.println(input);
                System.out.println("this is the array size: "+ size);
            }catch (IOException e) {
                System.out.println("Something went wrong in your reading file! ");
            }
        }

    }
Deadpool :

Since array is of fixed size you should know the size while creating, In below code gives ArrayIndexOutOfBoundException if there are more than 10 values in file

int[] input = new int[10]
 int i =0;
 while (myscan.hasNextLine()) {

    input[i]=myscan.nextInt();
     i++;
    }

So prefer using ArrayList<Integer>, to add the values from file, and later convert it to int array

int[] arr = input.stream().mapToInt(Integer::intValue).toArray();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159513&siteId=1