2008年6月13日 星期五

java讀檔筆記

這是一個binary Code 讀檔的範例,格式如下

1 Application status
12 FileName
8 Data Application
2 "\n\n"


長度共1+12+8+2 = 23

以下範例是長度會部是92,每個陣例長度為 23,所共陣例長度為4

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;


public class G2CLogFileRead {

private static final int len = 23;

public void run(){
String fileName = "/Users/macbook/java/test/REF00906.BVA";
run(fileName);
}

public void run(String fileName){

try {

File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();

int b = dis.read();

while (b > -1) {
bos.write(b);
b = dis.read();
}
byte[] ba = bos.toByteArray();

/* Every File length is 23 */
int fileSize = ((ba.length+1)/len);

String[] fName = new String[fileSize];
int k =0;
StringBuilder s = new StringBuilder();

for(int j = 1 ; j <= ba.length;j++){
s.append((char)(ba[j-1]));
if(j%len==0){
fName[k] = s.toString();
s.delete(0,len);
k++;
}
}

for(int f = 0 ; f< fName.length;f++){
System.out.print(fName[f]);
}


bos.close();
dis.close();

} catch (Exception e) {
System.out.println("IOException: " + e);
}

}


public void parseLog(int[] b) {

System.out.println(b);
}



/**
* @param args
*/
public static void main(String[] args) {

G2CLogFileRead g = new G2CLogFileRead();
/*
if ( args.length== 1 ){
String fileName = args[0];
}else{
System.out.println( "CPSLogTest filename");
return;
}

g.run(args[0]);
*/
g.run();

}

}

沒有留言: