我有一個記錄的二進制文件。每條記錄的格式如下: 每條記錄包含兩個整數,車輛數量和涉及的人數;浮點數,嚴重性代碼;和一個包含事故日期的字符串。此日期採用以下格式:三個字母的月份縮寫,後面跟一個空格,然後是一個月中的一天,後面跟一個逗號,最後一年可以用兩位數或四位數表示。如何在二進制文件中讀取整數和日期
以下是我沒有得到正確的答案code.But ..
我的代碼:
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
月4,2006 37966848 256 2.8513257442947E-311
月8,2011 38683904 512 2.3101107177838E-311君14,06 38683904 256 6.792508527386E-312月22,2005 38683904 256 1.2216329768334 E-311十月1,04 38683904 768 2.3099515681247E-311七月9,83 38813952 256 6.802588006634E-312 4月1998年 38813952 512 6.802588006634E-312 2011年6月14日 38813952 512 1.7667206456376E-311 09月08日99 車輛總數:576033218 總人數:540165485
請幫助我..預先提前!!
你確定整數是32位嗎?此外,'readDouble'方法將讀取64個字節的浮點信息。 – Greyson 2012-07-19 06:49:54
在你的輸出中你有日期,但是你沒有在你的代碼中讀到任何東西。你確定這段代碼產生了這個輸出嗎? – 2012-07-19 06:54:33
是整數是32位... – rupareliab 2012-07-19 12:04:26