【发布时间】:2012-07-19 06:42:34
【问题描述】:
我有一个二进制记录文件。每条记录的格式如下: 每条记录由两个整数组成,车辆数量和参与人数;浮点数,严重性代码;和一个包含事故日期的字符串。此日期采用以下形式:三个字母的月份缩写,后跟一个空格,然后是月份中的一天,后跟逗号,最后是可以用两位数或四位数字表示的年份。
以下是代码。但我没有得到正确的答案..
我的代码:
import java.io.*;
public class BoydBAssignment5_Ver1 {
public static void main(String s[]) {
DataInputStream input1; //you need these two variable for a file
File infile1;
input1 = null;
BoydBAssignment5_Ver1 tfr; //this is your program object
tfr = new BoydBAssignment5_Ver1();
try{ //try for open
infile1 = new File("assign5.data");
input1 = new DataInputStream(new FileInputStream(infile1));
} catch (IOException i){
i.printStackTrace();}
tfr.read_records(input1);
try { //try for close
input1.close();
} catch (IOException i) {
System.out.println("error in close");
}
}
private void read_records(DataInputStream is2) {
int totalVehicles=0,totalPersons=0;
int numVehicles;
int numPeople;
char ch;
try { //try for read
while(true) {
numVehicles=is2.readInt();
if(numVehicles==0)
break;
totalVehicles+=numVehicles;
System.out.print("\n"+numVehicles+"\t");
numPeople=is2.readInt();
if(numPeople==0)
break;
totalPersons+=numPeople;
System.out.print(numPeople+"\t");
System.out.print(is2.readDouble()+"\t");
/*System.out.print(is2.readLine()+"\n");
for(int k=0;k<4;k++)
{
is2.readByte();
}*/
while((ch=(char)is2.readByte()) != 0x00) {
System.out.print(ch+"");
}
}
System.out.println("\nTotal no of vehicles:"+totalVehicles);
System.out.println("Total no of Persons:"+totalPersons);
write_in_file(totalVehicles,totalPersons);
} catch (IOException i) {
System.out.println("error in write");
}
}
private void write_in_file(int totalVehicles, int totalPersons) {
try {
FileWriter fstream = new FileWriter("finalOutput.data");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Number of vehicles involved"+"\t"+totalVehicles);
out.write("\nNumber of persons involved"+"\t"+totalPersons);
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
输出 ::
148308 1 4.774904982E-314
189429102 540161068 1.4275957977117199E-71
512 576 6.903600071305329E-93 8,98 37966848 512 1.7668797952966E-311
2006 年 3 月 4 日 37966848 256 2.8513257442947E-311
2011年4月8日 38683904 512 2.3101107177838E-311 06 年 6 月 14 日 38683904 256 6.792508527386E-312 2005年4月22日 38683904 256 1.2216329768334E-311 10 月 1,04 38683904 768 2.3099515681247E-311 7 月 9,83 38813952 256 6.802588006634E-312 1998 年 8 月 4 日 38813952 512 6.802588006634E-312 2011 年 6 月 14 日 38813952 512 1.7667206456376E-311 99 年 9 月 8 日 39344128
车辆总数:576033218 总人数:540165485
请帮助我..提前谢谢!
【问题讨论】:
-
您确定整数是 32 位的吗?此外,
readDouble方法将读取 64 字节的浮点信息。 -
在您的输出中有日期,但您没有在代码中阅读任何内容。你确定这段代码会产生那个输出吗?
-
是的,这个给定的输出对应于代码,我已经编写了代码 while((ch=(char)is2.readByte()) != 0x00) { System.out.print(ch+" "); } 将日期读取为字符串读取..如果有任何其他方法请告诉我..请提前告诉我..