我编写了这段代码,它带有.txt文件并进行扫描。每一行代表一个具有其属性的独立进程。我需要能够循环遍历.txt文件的每一行,并为流程的字段分配不同的值。
这是我的流程类:
public class Process {
private String name;
private int arrive_time= 0;
private int burst_time = 0;
private int remain_time = 0;
public Process (String name, int arr_time, int bur_time) {
this.arrive_time = arr_time;
this.burst_time = bur_time;
this.remain_time = burst_time;
this.name = name;
}
public int getArrTime() {return arrive_time;}
public int getBurTime() {return burst_time;}
public int getRemTime() {return remain_time;}
public String getName() {return name;}
public void decRemTime() {this.remain_time--;}
}
这是我的.txt文件:
P1 0 8
P2 1 4
P3 2 9
P4 3 3
END 4 9999
p1应该被分配给第一个进程的name变量。 0是到达时间。 8是突发时间。然后我们移动到下一行,并为每次我移动到.txt中的新行时创建的新流程执行相同操作
这是我分配内容的代码:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Test {
public static void main(String[] args) {
//Priority queue for storing the initialized processes
PriorityQueue<Process> prq = new PriorityQueue<Process>(5, new Comparator<Process> () {
@Override
public int compare(Process p1, Process p2) {
return p1.getArrTime() - p2.getArrTime();
}
});
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("C:\\Users\\Veni\\Desktop\\test\\test.txt\\"));
}
catch (FileNotFoundException fnfex) {
System.out.println(fnfex.getMessage() + "File not found");
System.exit(0);
}
try {
int localProcessIndex = 0;
/* Count number of lines in .txt and store number in localProcessIndex.
* Then declare exactly that many processes.
*
* Then move to the loop below and start reading each line's values
* and start initialising the processes with those values.
*
* Then move all the processes to the prq priority queue.
*/
while((line = br.readLine()) != null) {
//Process localProcessIndex = new Process(line.split);
//System.out.println(line);
}
}
catch(IOException ioex) {
System.out.println(ioex.getMessage() + "Error reading");
}
SPN spn = new SPN(prq);
spn.SPN_ALG();
}
}
答案 0 :(得分:1)
假设您的文件始终具有相同的结构,您可以使用split(String regex)
方法处理数据:
while((line = br.readLine()) != null) {
try {
String[] params = line.split(" ");
prq.add(new Process(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]))),
...
}
catch(Exception e) {
//Log
}
}
编辑:您需要做的是拥有Process
项目列表。这将允许您创建所需的进程数量,并在稍后阶段使其可用。我修改了上面的代码以提供此功能。
答案 1 :(得分:1)
对于每一行,split
用空格。接下来使用parseInt
来获取数字。最后使用以下值调用构造函数:
String line = "P1 0 8";
String params = line.split("\s");
Process process = new Process(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]));