2011-09-06 49 views
0

我編寫VBA宏動隨機訪問文件,即創建隨機訪問模式文件:如何讀取在Java中

Private Type Record 
    id As Long 
    name As String * 20 
    status As String * 10 
End Type 

Private rec As Record 
Private rows_count As Long 
Private datfilePath As String 

Private Sub writeButton_Click() 
    datfilePath = ThisWorkbook.Path + "\data\datfile.dat" 
    datfile = FreeFile() 
    Open datfilePath For Random As #datfile Len = Len(rec) 

    rows_count = Int(LOF(datfile)/Len(rec)) 

    rec.id = rows_count + 1 
    rec.name = "test_name_" + Str(rows_count + 1) 
    rec.status = "test_sta" + Str(rows_count + 1) 

    Put #datfile, rows_count + 1, rec 

    rows_count = Int(LOF(datfile)/Len(rec)) 

    Close #datfile 
End Sub 

如何閱讀在java中創建的文件?

+1

你知道是什麼文件格式,它結束了內部使用?字符串是如何表示的,Long是如何表示的?一旦你解決了這個問題,其他問題應該相當容易。 –

+0

檢查教程。提示:'FileInputStream'用於從Java中的文件讀取數據。 – Lynch

回答

0

的結果:

import java.io.*; 

class ReadVBFile { 
    public static void main(String[] args) throws IOException{ 
    try 
    { 
     String file = "datfile.dat"; 

     RandomAccessFile fh = new RandomAccessFile(file,"r"); 

     int file_length =(int)fh.length(); 
     int rec_length = 34; 
     int rec_count = (int)(file_length/rec_length); 

     System.out.println("file_length: " + file_length + "\r\n"); 
     System.out.println("rec_count: " + rec_count + "\r\n"); 

     for(int i_row=0; i_row < rec_count; i_row++) 
     { 
     byte[] id_array = new byte[4]; 
     byte[] name_array = new byte[20]; 
     byte[] status_array = new byte[10]; 

     for(int i=0; i < 34; i++) 
     { 
      byte b = fh.readByte(); 
      if(i < 4) 
      { 

      id_array[i] = b; 
      } 
      else if(i < 24) 
      { 
      name_array[i-4] = b; 
      } 
      else if(i < 34) 
      { 
      status_array[i-24] = b; 
      } 

      fh.seek(i_row*34 + i + 1); 
     } 

     // Long as Int 
     int myInt = ((id_array[1] & 0xff) << 24) | ((id_array[2] & 0xff) << 16) | ((id_array[3] & 0xff) << 8) | (id_array[0] & 0xff); 
     String name_value = new String(name_array); 
     String status_value = new String(status_array); 

     System.out.println(myInt + ", '" + name_value + "', '" + status_value + "'"); 
     } 
    } 
    catch(IOException e) 
    { 
     System.out.println("IOException: " + e.getMessage()); 
    } 
    catch(Exception e) 
    { 
     System.out.println("Exception: " + e.getMessage()); 
    }  
    } 
}