JAVA-从txt文件进行数据的读取与写入
public List<ServiceEvent> readSerListFromTXT(String fileName){
List<ServiceEvent> serviceEventList = new ArrayList<ServiceEvent>();
BufferedReader inputStream = null;
boolean isFirstLine = true;
try {
inputStream = new BufferedReader(new FileReader(fileName));
String line;
while((line = inputStream.readLine()) != null){
String[] nodeRow = line.split("\\s+");
//EventType eventType, int eventId, double arriveTime, double holdTime, int src, int dst, int transmissionRate ServiceEvent ser = new ServiceEvent();
if (isFirstLine){
isFirstLine = false;//第一行是说明,所以读的时候要跳过 continue;
}
for (int j = 0; j < nodeRow.length; j++) {
switch (j){
case 0: {
if (nodeRow[j].equals("SERVICE_ARRIVAL")){
ser.setEventType(EventType.SERVICE_ARRIVAL);
}else if (nodeRow[j].equals("SERVICE_END")){
ser.setEventType(EventType.SERVICE_END);
}
break;
}
case 1: ser.eventId = Integer.parseInt(nodeRow[j]);break;
case 2: ser.setArriveTime(Double.parseDouble(nodeRow[j]));break;
case 3: ser.setHoldTime(Double.parseDouble(nodeRow[j]));break;
case 4: ser.setSrc(Integer.parseInt(nodeRow[j]));break;
case 5: ser.setDst(Integer.parseInt(nodeRow[j]));break;
case 6: ser.setTransmissionRate(Integer.parseInt(nodeRow[j]));break;
default:break;
}
}
serviceEventList.add(ser);
}
} catch(Exception e){
System.out.println(e);
}
return serviceEventList;
}
public void writeSerListToTXT(String fileName,List<ServiceEvent> serList){
System.out.println(fileName);
int rowNum = serList.size();
int columnNum = 7;
//EventType eventType, int eventId, double arriveTime, double holdTime, int src, int dst, int transmissionRate try {
FileWriter fw = new FileWriter(fileName);
fw.write("eventType, eventId , arriveTime, holdTime, src, dst, transmissionRate"+"\n");
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < columnNum; j++){
switch (j){
case 0: fw.write(serList.get(i).getEventType()+ "\t"); break;
case 1: fw.write(serList.get(i).getEventId()+ "\t"); break;
case 2: fw.write(serList.get(i).getArriveTime()+ "\t"); break;
case 3: fw.write(serList.get(i).getHoldTime()+ "\t"); break;
case 4: fw.write(serList.get(i).getSrc()+ "\t"); break;
case 5: fw.write(serList.get(i).getDst()+ "\t"); break;
case 6: fw.write(serList.get(i).getTransmissionRate()+ "\t"); break;
default: break;
}
}
fw.write("\n");
}
fw.close();
}
catch (IOException e){
e.printStackTrace();
}
}