BKCommonLib/FileData

From BergerHealer Wiki
Revision as of 21:20, 8 June 2021 by RyanDo (talk | contribs) (Created page with "« Go back ==Introduction== To make raw data storage possible without the common try-catch logic blurring your vision, there are data reading and writing clas...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

« Go back

Introduction

To make raw data storage possible without the common try-catch logic blurring your vision, there are data reading and writing classes to help you. IO exceptions, missing files or access errors are automatically dealt with.

Usage

To use it, create a new instance of the class (nested class), implement the read/write methods and call read() or write() at the end. Examples:

DataReader
new DataReader(filename) {
    public void read(DataInputStream stream) throws IOException {
        final int count = stream.readInt();
        for (int i = 0; i < count; i++) {
             data.add(stream.readInt());
        }
    }
}.read();
DataWriter
new DataWriter(filename) {
    public void write(DataOutputStream stream) throws IOException {
        int count = stream.writeInt(data.size());
        for (Integer val : data) {
            data.writeInt(val.intValue());
        }
    }
}.write();

Compressed DataReader/DataWriter

The exact same code, only use the respective classes instead. The data is compressed using a DeflaterOutputStream and decompressed using a InflaterInputStream

Notes

You are using nested classes here, which means that it is not possible to access all variables 'just like that'. To access a variable from within read or write, you have several options:

Declare them statically or provide a way to access them statically (getInstance()) Declare the variables final Example of final variables being used this way:

public void writeMyValue(String filename) {
    final int value = this.getSpecialValue(); // Variable is final, therefore we can access it
    new DataWriter(filename) {
        public void write(DataOutputStream stream) throws IOException {
            stream.writeInt(value);
        }
    }.write();
}