Запись и добавление в файл .dat - PullRequest
0 голосов
/ 02 февраля 2020

Я написал класс, способный читать файл .dat и выводить содержимое на экран, чтобы я мог их прочитать. Пока что здесь печатается все необходимое для проверки.

public class WriteDefinitions {

    private static String   SHOP_NAME_CONTAINS = "Example";
    private static Integer  SHOP_ITEM_ID = 0;
    private static Integer  SHOP_QTY_AMT = 0;
    //private static int[][]    NEW_ITEMS = new int[][] { {itemId, itemQty}, {itemId, itemQty} };
    private static int[][]  NEW_ITEMS = new int[][] { {3, 10}, {4, 10} };

    public static void main(String[] args) {
        if(SHOP_NAME_CONTAINS != "") pullShopInformation();
    }

    private static void pullShopInformation() {
        int lineNumber = 0;
        try {
            byte abyte2[] = FileOperations.readFile("./data/content/Shops.dat");
            Stream stream2 = new Stream(abyte2);
            lineNumber = stream2.readUnsignedWord();
            System.out.println("Total shops: " + lineNumber);
            System.out.println("");
            for (int i = 0; i < lineNumber; i++) {
                String name = stream2.readString();
                if(name.contains(SHOP_NAME_CONTAINS)) {
                    int type = stream2.readUnsignedByte();
                    int listOfShopItems = stream2.readUnsignedByte();
                    for (int j = 0; j < listOfShopItems; j++) {
                        int itemId = stream2.readUnsignedWord();
                        int itemQty = stream2.readUnsignedWord();
                        System.out.println("Shop #: " + i + "   |   Item #: " + itemId + "  |   Qty: " + itemQty);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Вот распечатка магазина с именем Example

Shop #: 110 |   Item #: 8   |   Qty: 10
Shop #: 110 |   Item #: 6   |   Qty: 0
Shop #: 110 |   Item #: 12  |   Qty: 10
Shop #: 110 |   Item #: 10  |   Qty: 10
Shop #: 110 |   Item #: 4   |   Qty: 10
Shop #: 110 |   Item #: 5   |   Qty: 10

Как я могу внести изменения в файл .dat?

В вышеприведенном распечатке для магазина № 110 пункт 6 имеет количество 0. Как я могу обновить количество внутри .dat до 10? Кроме того, как мне добавить новые предметы (NEW_ITEMS [] []) в конкретный c магазин или даже создать новый магазин вообще?

Я понимаю, что мне нужно использовать writeFile (), но я пытаюсь понять, как его использовать. FileOperations.writeFile(".data/content/Shops.dat", newItemQty?);

Я использую DataInputStream для чтения файла. Вот класс FileOperations.

public class FileOperations {


    public FileOperations() {
    }

    public static final byte[] readFile(String s) {
        try {
            File file = new File(s);
            int i = (int)file.length();
            byte abyte0[] = new byte[i];
            DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(s)));
            dataInputStream.readFully(abyte0, 0, i);
            dataInputStream.close();
            totalRead++;
            return abyte0;
        } catch(Exception exception) {
            System.out.println((new StringBuilder()).append("Read Error: ").append(s).toString());
        }
        return null;
    }

    public static final void writeFile(String s, byte abyte0[]) {
        try {
            (new File((new File(s)).getParent())).mkdirs();
            FileOutputStream fileOutputStream = new FileOutputStream(s);
            fileOutputStream.write(abyte0, 0, abyte0.length);
            fileOutputStream.close();
            totalWrite++;
            completeWrite++;
        } catch(Throwable throwable) {
            System.out.println((new StringBuilder()).append("Write Error: ").append(s).toString());
        }
    }

    public static boolean fileExists(String file) {
    File f = new File(file);
        if(f.exists()) {
            return true;
        } else {
            return false;
        }
    }


    public static int totalRead = 0;
    public static int totalWrite = 0;
    public static int completeWrite = 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...