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

问题描述 投票:2回答:1

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

    }
java arrays file java.util.scanner bufferedreader
1个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.