解析具有特定文件格式

时间:2017-05-21 10:24:03

标签: java parsing

嗨,我对java比较陌生,我想知道如何将某种文件格式解析为2D数组。

文件格式由逗号分隔值和<和/>分离一组附加值。

<a,b,c/><x,y,z>
<...
<...

然后将每行输入到数组[] []中,其中第一组将进入第一列而下一组将进入第二列。

然后输出该行看起来像这样。

a, b, c
x ,y ,z
...

任何帮助都会非常感谢。

编辑:这是我到目前为止所拥有的

public static main (String args[])
{
    //Open file, read to get number of lines of file = numLine

    int[][] array = new int[numLine][numLine]

    for (int i = 0; i < numLine; i++)
    {
        //Unsure how to write element/line split
        array[i][i] = //input each element to array
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以根据需要进行修改。我添加了一些评论,因此您可能需要注意它们。

    Scanner sc = new Scanner(file);

    String[][] array = new String[numLine][numLine];//declaring the matrix

    int r=0 , c=0;//declaring the index of the matrices column and row

    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        line = line.replaceAll("[<>]", "");//removing > and < so we gonna have a,b,c/x,y,z
        String[] col = line.split("/");// spliting using / and we gonna have  a,b,c    x,y,z

        for (String row : col) {
            //a,b,c or x,y,z
            String[] oneCol = row.split(",");
            for (String oneRow : oneCol) {
                if(c >= numLine){
                    c = 0;
                    break;
                }
                array[r][c] = oneRow;
                c++;
            }
            r++;
            //System.out.println();
        }
        c = 0;

    }

    sc.close();

答案 1 :(得分:0)

正如@Young Millie指出的,到目前为止你有什么尝试?话虽如此,您可以采取以下几种方法,其中一种方法如下。

有效的尝试是逐行读取文件,然后使用replaceAll(...)删除所有符号(这将进一步解释为in their java docs),但您可以使用以下替换:< / p>

String line = "<a,b,c/><x,y,z>";
line = line.replaceAll("[<>]", "");
System.out.println("1. " + line);

结果为:

1. a,b,c/x,y,z

然后我们将字符串拆分为“/”,从而产生两个必需字符串数组:

String[] lines = line.split("/");
System.out.println("1. " + lines[0]);
System.out.println("2. " + lines[1]);

结果为:

1. a,b,c
2. x,y,z