使用BufferedReader将文件内容存储在Integer的ArrayList中

我要存储以下格式的文本文件的内容:

第一行包含2个整数,例如n和k,以空格分隔。

以下几行包含n个整数(n可以非常大)(我想将其存储在ArrayList中)

通过在线搜索有关Java中文件处理方式的知识,我了解到BufferedReader是处理大输入时的首选方式,因为它更快(与Scanner相比)以及如何执行。我的尝试如下:

public static void main(String[] args) throws IOException {
        StringBuilder t = new StringBuilder();
        try(BufferedReader br = Files.newBufferedReader(Paths.get("./interview1.txt"))) {
            t.append(br.readLine());
            String[] firstLine = new String[2];
            firstLine = t.toString().split(" ");
            int n = Integer.parseInt(firstLine[0]);
           // System.out.println(n);
            int k = Integer.parseInt(firstLine[1]);
           // System.out.println(k);
            String line;
            List<Integer> list = new ArrayList<>(n);
            while((line = br.readLine()) != null){
                String[] thisLine = line.split(" ");
                for(int i = 0; i < thisLine.length; i++){
                   // System.out.print(thisLine[i] + " ");
                   list.add(Integer.valueOf(thisLine[i]));
                }
            }
        } catch (Exception e) {
            System.err.format("IOException: %s%n",e);
        }

由于我知道第一行仅包含2个数字,因此我读取了该行,将其转换为大小为2的String数组,然后将2个Integer分开。到目前为止一切都很好。

在进入while循环之后,问题接着出现。在尝试将内容添加到列表中时,我不断收到java.lang.NumberFormatException(据我所知,这意味着我尝试将不包含可解析的int的String转换为Integer)。>

在for循环中取消注释第一行将产生以下输出:

3 4 2 1 6 7 1 2 2 3 (extra random 2 towards the end??)

当前使用的文件内容:

10 5
3 4 2 1 6 7 1 2 3

我在做什么错了?

lic1234567890 回答:使用BufferedReader将文件内容存储在Integer的ArrayList中

您似乎可以使用java.nio,因此我建议尽可能多地使用它的功能并摆脱BufferedReader

我的示例文件 numbers.txt 看起来像这样:

1 2 14 55 165
2
3 4  5  6    7
4

6
7 8 9 10 11 12 13 14 15 16 17

您可以阅读并在List<Integer>中将每一行的数字存储在单独的List<List<Integer>>中,也可以将在该文件中读取的所有数字存储在单个List<Integer>中。检查以下代码及其注释:

public static void main(String[] args) {
    // provide the path to the file
    Path pathToFile = Paths.get("Y:\\our\\path\\to\\numbers.txt");
    // provide a list of lists of numbers
    List<List<Integer>> numbersInLines = new ArrayList<>();
    // or provide a single list of integers
    List<Integer> allNumbers = new ArrayList<>();

    // try reading the file,you may want to check if it exists and is valid before
    try {
        Files.lines(pathToFile).forEach(line -> {
            // provide a list for the numbers of each line
            List<Integer> realNumbers = new ArrayList<>();
            // split the line by an arbitrary amount of whitespaces
            String[] lineElements = line.trim().split("\\s+");
            // convert them to integers and store them in the list of integers
            for (String lineElement : lineElements) {
                // check if there is an empty String
                if (!"".equals(lineElement)) {
                    // add it to the list of the current line
                    realNumbers.add(Integer.valueOf(lineElement));
                    // and / or add it to the list of all numbers
                    allNumbers.add(Integer.valueOf(lineElement));
                }
            }
            // store the list of numbers of the current line in the list of lists
            numbersInLines.add(realNumbers);
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    // print each line list
    numbersInLines.forEach(lineNumbers -> {
        lineNumbers.forEach(System.out::print);
        System.out.println();
    });

    // and / or print all the numbers in a single line,separated by a whitespace
    allNumbers.forEach(number -> System.out.print(number + " "));
}

输出将是这样:

121455165
2
34567
4

6
7891011121314151617
1 2 14 55 165 2 3 4 5 6 7 4 6 7 8 9 10 11 12 13 14 15 16 17 
本文链接:https://www.f2er.com/2994881.html

大家都在问