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

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

我如何从一个包含大量数字的文本文件中读取并将其存储到一个 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! ");
            }
        }

    }

由于数组的大小是固定的,因此您应该在创建时知道大小,如果文件

中的值超过 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();