繁体   English   中英

如何从文本文件中读取并存储到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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM