我有一個用於我正在更新的DOS程序的配置文件。 。 。從數組讀取字節數組到Java數組
配置文件爲17512字節。前128個字節是標題信息,其餘字節被分成256個記錄,每個記錄64個字節。每個記錄包含名稱(8字節),描述(18字節),單元號(1字節)等設備的特定信息。我正在將文件讀取到一個大字節數組中,然後想要提取單個設備信息,以便可以在新的GUI界面中對其進行編輯。
我創建了一個包含設備名稱字段的Device類。我想創建一個包含所有256個設備的類的數組,但是當我嘗試讀取各個設備名稱時,所有256個設備都會以最後讀取的設備結束。我不確定我出錯的地方。
這裏是Main.java
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
ReadConfigFile.importConfigFile(); // Read config file into byte array.
Device[] device = new Device[256]; // Create array of 256 Devices.
device[0].code = Device.setCode(0);
System.out.println(new String(device[0].code)); // First device correct here.
device[255].code = Device.setCode(255);
System.out.println(new String(device[0].code)); // First device now same as last?
System.out.println(new String(device[255].code));
Group root = new Group();
Scene scene = new Scene(root, 200, 200);
primaryStage.setTitle("Config File Editor");
primaryStage.setScene(scene);
primaryStage.show();
}
}
的代碼下面是該類設備的代碼。到目前爲止,我只有第一個領域。當我能夠正常工作時,我會添加其餘的。
public class Device {
public static byte[] code; // 8 bytes. (1 - 8).
public Device() {
code = new byte[8]; // Constructor correct?
}
public static byte[] setCode(int devNumber) {
int devCodeByteStart = (128 + (64 * devNumber)); // Skip first 128 bytes to get to first device.
int devCodeByteStop = (devCodeByteStart + 8); // Get 8 bytes for device code.
byte[] code = new byte[8]; // Gives Null Pointer Exception if removed.
for(int byteCount = devCodeByteStart; byteCount < devCodeByteStop; byteCount++) {
code[byteCount - devCodeByteStart] = configFileBytes[byteCount];
}
return code;
}
}
如果有更好的方法來完成任務,我願意接受建議。
你知道什麼是'static'意味着/呢? – Amit
@Amit haha ...這麼簡單... :) –
Device的所有實例共享相同的代碼數組,因爲您聲明爲靜態。 – JJF