如何读取格式化的图形数据文件Java

时间:2019-03-31 08:38:02

标签: java input graph format

我正在读取adj矩阵的图形数据,并且采用以下方式对其进行格式化:

0
   176     67
   665    185
  1129     26
  1414    114
  1748    205

1
   140    248
   591    175
  1920     68
  2229     31

2
   778    476
   825    447
   888    258
  1179   ....

单个数字线是起始顶点,然后是具有边长的终止顶点线

0-起始顶点

176-最终顶点

67-边长

665-最终顶点

185-边长

,依此类推 那就是我尝试过的:

public void ValueAssign()
         throws IOException {
         Scanner inFile = new Scanner(new File("list1.txt"));
         String s = inFile.nextLine();
         int NofV = Integer.parseInt(s); // number of vertices
         int NofE = Integer.parseInt(s); // number of edges
         int v1,v2, edge; // v1 - vertex 1, v2 - vertex 2
         while ((s = inFile.nextLine()) != null) {

             Scanner in = new Scanner(s);
             in.useDelimiter(" ");
             v2 = in.nextInt();
             edge = in.nextInt();
         }


    }

我怎么读?

1 个答案:

答案 0 :(得分:0)

尝试此代码

public static void main(String[] args) throws FileNotFoundException {
    Scanner inFile = new Scanner(new File("list1.txt"));
    int startingVertex, endingVertex, edgeLength;
    while (inFile.hasNextLine()) {
        String trimmedLine = inFile.nextLine().trim();

        //Skip empty lines
        if(trimmedLine.isEmpty()){
            continue;
        }

        String values[] = trimmedLine.split("\\s+");

        if(values.length > 1){
            endingVertex = Integer.parseInt(values[0]);
            edgeLength = Integer.parseInt(values[1]);

            //Do necessary operations

        }else if(values.length > 0){
            startingVertex = Integer.parseInt(values[0]);

            //Do necessary operations

        }
    }
}