如何从文本文件读取并存储到Java中的数组

时间:2019-03-05 04:11:35

标签: java arrays file java.util.scanner bufferedreader

如何从包含大量数字的文本文件中读取并将其存储到int数组中,最后我将该数组和该数组的大小传递给将在我的应用程序中使用的其他方法。 到目前为止,我的代码从文本文件读取并将其存储到ArrayList而不是数组中。 谢谢。

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 个答案:

答案 0 :(得分:1)

由于数组的大小是固定的,因此在创建时应该知道大小,在下面的代码中,如果文件中的值超过10,则给出ArrayIndexOutOfBoundException

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

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

因此,更喜欢使用ArrayList<Integer>从文件中添加值,然后将其转换为int数组

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