java中不同起始和结束分隔符的io读取文件

bnlyeluc  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(290)

我正在尝试实现会议调度算法。我想随机生成会议并将其存储在文件中。然后在另一个代码中读取此文件,创建不同的代理来安排这些会议。
我的输入会议文件如下:

1  20  25  [1, 2, 3, 4, 5]  [4, 5]

2  21  29  [1, 6, 7, 5, 33]  [1, 5, 33]

从左到右,这些值表示会议id、开始时间、硬截止日期、与会者id列表、重要与会者id列表。
基本上它是整数和整数数组列表的组合(动态的,大小不是固定的)。为了存储这个,我使用了这个代码

File fleExample = new File("Meeting.txt")
PrintWriter M1 = new PrintWriter(fleExample);
M1.print(m.getMeetingID()+" "+m.getStartTime()+" "+m.getHardDeadLine()+" "+m.getAttendees()+" "+m,getEssentialAttendees());
M1.println();

我想读取这些值并将其设置为integer variables和integer arraylist。

FileInputStream fstream = new FileInputStream("Meeting.txt");
  DataInputStream inp = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(inp));
  String strLine;
  while ((strLine = br.readLine()) != null)   {
        String[] tokens = strLine.split(" ");
        for (int i = 0; i < MeetingCount; i++) {
               Meeting meet = new Meeting();
               meet.setMeetingID(Integer.valueOf(tokens[0]));
               meet.setStartTime(Integer.valueOf(tokens[1]));
               meet.setHardDeadLine(Integer.valueOf(tokens[2]));
        }
   }

我可以将值设置为整数,但找不到对arraylist执行相同操作的方法。我想将字符串存储到arraylist。在这个方向上任何帮助都将是巨大的。

ff29svar

ff29svar1#

我不太清楚你的实现是为了什么(以及 Meeting 对象),但如果您只想将它们赋给int或list变量,请尝试使用扫描仪逐个读取它们:

String str = "1 20 25 [1 2 3] [4 5]";

Scanner scan = new Scanner(str);
int intVariable = 0;
ArrayList<Integer> listVariable = null; //null marks no active list

while (scan.hasNext()) { //try/catch here is highly recommeneded!

    //read next input (separated by whitespace)
    String next = scan.next();

    if (next.startsWith("[")) {
        //init new list and store first value into it
        listVariable = new ArrayList<Integer>();
        listVariable.add(Integer.parseInt(next.substring(1)));
    } else if (next.endsWith("]")) {
        //add the last item to the list
        listVariable.add(Integer.parseInt(next.substring(0, next.length()-1)));
        System.out.println(Arrays.toString(listVariable.toArray()));
        //reset the list to null
        listVariable = null;
    } else {
        //if inside a list, add it to list, otherwise it is simply an integer
        if (listVariable != null) {
            listVariable.add(Integer.parseInt(next));
        } else {
            intVariable = Integer.parseInt(next);
            System.out.println(intVariable);
        }
    }
}

这里我只是打印了输出,但是您当然可以将其投影到任何需要的地方,或者有一个整数值列表和一个整数值列表。
另外请注意,在这个示例中,我只获取了文件的一行,但是您可以直接向scanner提供您的文件(无需自己逐行读取)。
希望这有帮助。

wlsrxk51

wlsrxk512#

String fileinput="2 21 29 [6 7] [71 45 33]";
Pattern p=Pattern.compile("[0-9]+");    
Matcher m=p.matcher(fileinput);
while (m.find()) {
    int i=Integer.parseInt(fileinput.substring(m.start(), m.end()));
    System.out.println(i);
}

上面的问题是通过使用正则表达式来解决的,正则表达式连续搜索一个或多个整数,当它们找不到更多整数时中断。这个过程会一直重复到字符串结束。m、 find将返回所标识模式的开始和结束位置。使用起始值和结束值,我们从主字符串中提取子字符串,然后作为整数进行解析。

相关问题