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

问题: 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 metho...

问题:

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! ");
            }
        }

    }

回答1:

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();
  • 发表于 2019-03-06 15:13
  • 阅读 ( 222 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除