如何读取文件然后将每个文件整数分配给数组列表?

时间:2016-09-01 18:46:40

标签: java arrays arraylist file-io nullpointerexception

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class NotWorking {   
    public static void main(String[] args) throws Exception{
        // The files that I need to open
        // They contain integers (points on a graph)
        // Ex: 74 0 80 100 150 60 150
        String[] names = {"Test.txt", "Test2.in", "test3.in", "Test4.in", "Test5.in"};
        // Create 5 list
        ArrayList<Integer>[] textFiles = new ArrayList[5];

        // for loop through each file
        for (int i = 0; i < names.length; i++) {
            Scanner scanner;
            // open file
            scanner = new Scanner(new File(names[i]));
            // @fileNumber is one of 5 list
            int fileNumber = 0;
            // add each integer to the correct list
            while (scanner.hasNextInt()){
            // line below this is where it says NullPointer Exception
            textFiles[fileNumber].add(scanner.nextInt());       
            }enter code here
            // Trying to see if lists are made correctly and also increasing fileNumber after
            // each file is processed
            System.out.println(textFiles[fileNumber]);
            fileNumber ++;      
        }   
    }
    }

我需要打开以数组形式提供的文件(.txt和.in)。我使用for循环遍历它们然后打开它们,但是当我读完它们时,我想使用它们中的数据。所以我的想法是创建5个数组列表并将数据放入其中。但我似乎无法弄明白。它一直给我NullPointer异常。此外,我需要能够将数据放入另一种方法。一个例子是&#34; Quad(ax,ay,bx,by,cx,cy,dx,dy)&#34;每个文件都有我需要的坐标。数组列表是完成它的最佳方法吗?

2 个答案:

答案 0 :(得分:0)

您的代码非常低级 - 为您提供一些“起点”来处理更有用的抽象:

所有文件中的所有行读入单个List<String>可能要容易得多(假设所有文件都具有相同的格式)。< / p>

使用Files.readAllLines()

可以轻松实现这一目标

除非这是家庭作业,否则你会被要求“手动”;你真的应该依赖这种高水平的抽象。实施已经存在的东西没有多大意义。不这样做的另一个原因是,如果你在谈论巨大的文件;所以你只想在同一个时间点内存所有那些行。

即使您不使用readAllLines一次性读取所有文件;您仍然可以使用该方法在一次性中一个接一个地读取一个文件。

无论您如何收集信息;然后你有一个包含原始数据的List<String>;现在可以使用regular expressions轻松匹配这些字符串中的数字;然后使用Integer.parseInt()将它们转换为int。简单的例子:

String numbersAsString = "1 2 3 4";
String[] separatedNumbers = numbersAsString.split(" ");
List<Integer> numbers = new ArrayList<>();
for (String oneNumber : separatedNumbers) {
  numbers.add(Integer.parseInt(oneNumber));
}

最后,将4个整数或整数转换成其他字符串表示非常简单;像:

String toQuad(int a, int b, ....... ) {
  return "Quad(" + a +"," + b ...

答案 1 :(得分:0)

在使用它们之前,您需要为arraylists分配内存。

这就是为什么它抛出NullPointerException的原因,因为textFiles [0],...为null,而你正试图对null执行操作!

textFiles[fileNumber] = new ArrayList<Integer>();  
// call constructor as above to allocate memory to each individual arraylists.
while (scanner.hasNextInt()){   
        textFiles[fileNumber].add(scanner.nextInt());       
        }