Java从文件中读取2D数组,用逗号分隔的数字

时间:2014-01-23 05:32:55

标签: java arrays split 2d delimiter

这是我发现的一些帮助读取2D数组的代码,但我遇到的问题是这只会在读取数字列表时才会起作用:

73
56
30
75
80
ect..

我想要的是能够读取多个结构如下的行:

1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1

我只想基本上将每一行作为数组导入,同时将它们构造成文本文件中的数组。 我读过的所有内容都说使用scan.usedelimiter(“,”);但在我尝试使用它的任何地方,程序直接抛出回复“错误转换数字”的捕获。如果有人可以提供帮助,我会非常感激。我还看到了一些关于为缓冲读卡器使用split的信息,但我不知道哪个更适合使用/为什么/如何。

    String filename = "res/test.txt"; // Finds the file you want to test.


    try{
        FileReader ConnectionToFile = new FileReader(filename);
        BufferedReader read = new BufferedReader(ConnectionToFile);
        Scanner scan = new Scanner(read);

        int[][] Spaces = new int[10][10];
        int counter = 0;
        try{
            while(scan.hasNext() && counter < 10)
            {
                for(int i = 0; i < 10; i++)
                {
                    counter = counter + 1;
                    for(int m = 0; m < 10; m++)
                    {
                        Spaces[i][m] = scan.nextInt();
                    }
                }
            }
            for(int i = 0; i < 10; i++)
            {
                //Prints out Arrays to the Console, (not needed in final)
                System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
            }
        } 
        catch(InputMismatchException e)
        {
            System.out.println("Error converting number");
        }
        scan.close();
        read.close();
    }
    catch (IOException e)
    {
    System.out.println("IO-Error open/close of file" + filename);
    }
}

5 个答案:

答案 0 :(得分:0)

以下代码段可能会有所帮助。基本思想是读取每一行并解析出CSV。请注意,CSV解析通常很难,并且主要需要专门的库(例如CSVReader)。但是,手头的问题相对简单。

try {
   String line = "";
   int rowNumber = 0;
   while(scan.hasNextLine()) {
       line = scan.nextLine();
       String[] elements = line.split(',');
       int elementCount = 0;
       for(String element : elements) {
          int elementValue = Integer.parseInt(element);
          spaces[rowNumber][elementCount] = elementValue;
          elementCount++;
       } 
       rowNumber++;
   }
} // you know what goes afterwards

答案 1 :(得分:0)

因为它是一个逐行读取的文件,所以使用分隔符“,”读取每一行。

所以在这里你只需创建一个新的扫描仪对象,使用分隔符“,”

传递每一行

代码如下所示,首先是for循环

           for(int i = 0; i < 10; i++)
                {
                    Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
                    counter = counter + 1;
                    for(int m = 0; m < 10; m++)
                    {
                        Spaces[i][m] = newScan.nextInt();
                    }
                }

答案 2 :(得分:0)

为什么要将扫描仪用于文件?您已经有BufferedReader

FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);

现在您可以逐行读取文件。棘手的一点是你想要一个int

的数组
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
    String[] array = line.split(",");
    for (int i = 0; i < array.length; i++)
    {
        spaces[row][i] = Integer.parseInt(array[i]);
    }
    row++;
}

另一种方法是使用Scanner表示各行:

while ((line = reader.readLine()) != null)
{
    Scanner s = new Scanner(line).useDelimiter(',');
    int col = 0;
    while (s.hasNextInt())
    {
        spaces[row][col] = s.nextInt();
        col++;
    }
    row++;
}

另一件值得注意的事情是你正在使用int[10][10];这需要您事先知道文件的长度。 List<int[]>会删除此要求。

答案 3 :(得分:0)

使用Scanner中的useDelimiter方法将分隔符设置为“,”而不是默认空格字符。 根据给定的示例输入,如果2D数组中的下一行以新行开头,而不是使用“,”,则必须指定多个分隔符。

示例:

 scan.useDelimiter(",|\\r\\n");

这将分隔符设置为“,”和回车+新行字符。

答案 4 :(得分:0)

我在这里提供我的代码。

public static int[][] readArray(String path) throws IOException {
    //1,0,1,1,0,1,0,1,0,1
    int[][] result = new int[3][10];
    BufferedReader reader = new BufferedReader(new FileReader(path));
    String line = null;
    Scanner scanner = null;
    line = reader.readLine();
    if(line == null) {
        return result;
    }
    String pattern = createPattern(line);
    int lineNumber = 0;
    MatchResult temp = null;
    while(line != null) {
        scanner = new Scanner(line);
        scanner.findInLine(pattern);
        temp = scanner.match();
        int count = temp.groupCount();
        for(int i=1;i<=count;i++) {
            result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
        }
        lineNumber++;
        scanner.close();
        line = reader.readLine();
    }
    return result;
}

public static String createPattern(String line) {
    char[] chars = line.toCharArray();
    StringBuilder pattern = new StringBuilder();;
    for(char c : chars) {
        if(',' == c) {
            pattern.append(',');
        } else {
            pattern.append("(\\d+)");
        }
    }
    return pattern.toString();
}