文件与偏好数据库


1 文件

1.1 写文件

try {
    File file = new File(getFilesDir() + "/notes.txt");
    FileOutputStream fos = new FileOutputStream(file);
    String string = textField.getText();
    byte[] bytes = string.getBytes();
    fos.write(bytes);
    fos.close();
}
catch (Exception exception) {
    exception.printStackTrace();
}

1.2 读文件

try {
    File file = new File(getFilesDir() + "/notes.txt");
    FileInputStream fis = new FileInputStream(file);
    byte[] bytes = new byte[(int)file.length()];
    fis.read(bytes);
    fis.close();
    String string = new String(bytes);
    textField.setText(string);
}
catch (Exception exception) {
    exception.printStackTrace();
}

例程:File

...\File\entry\src\main\resources\base\graphic\background_scrollview.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="50"/>
    <solid ohos:color="#ffffff"/>
    <stroke ohos:width="2vp" ohos:color="#ff7f27"/>
</shape>

...\File\entry\src\main\resources\base\graphic\background_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners ohos:radius="50"/>
    <solid ohos:color="#ff7f27"/>
</shape>

...\File\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical"
    ohos:background_element="#00a2e8">

    <ScrollView
        ohos:height="match_parent"
        ohos:weight="1"
        ohos:width="match_parent"
        ohos:padding="10vp"
        ohos:left_margin="20vp"
        ohos:right_margin="20vp"
        ohos:top_margin="20vp"
        ohos:background_element="$graphic:background_scrollview"
        ohos:rebound_effect="true">

        <TextField
            ohos:id="$+id:tf"
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:multiple_lines="true"
            ohos:hint="编辑文件"
            ohos:text_size="20fp"
            />

    </ScrollView>

    <Button
        ohos:id="$+id:btn"
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:padding="$ohos:float:button_radius"
        ohos:margin="20vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="保存"
        ohos:text_size="22fp"
        ohos:text_color="#ffffff"
        />

</DirectionalLayout>

...\File\entry\src\main\java\com\minwei\file\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    private TextField textField;
    private Button button;

    @Override
    public void onStart(Intent intent) {
        ...
        textField = (TextField)findComponentById(ResourceTable.Id_tf);
        button = (Button)findComponentById(ResourceTable.Id_btn);

        read();

        button.setClickedListener(component -> save());
    }
    ...
    private void read() {
        try {
            File file = new File(getFilesDir() + "/notes.txt");
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[(int)file.length()];
            fis.read(bytes);
            fis.close();
            String string = new String(bytes);
            textField.setText(string);
        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    private void save() {
        try {
            File file = new File(getFilesDir() + "/notes.txt");
            FileOutputStream fos = new FileOutputStream(file);
            String string = textField.getText();
            byte[] bytes = string.getBytes();
            fos.write(bytes);
            fos.close();
        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

运行效果如下图所示:

2 图像文件

ResourceManager manager = getResourceManager();
RawFileEntry entry = manager.getRawFileEntry(
    "resources/rawfile/image.jpg");

try {
    InputStream is = entry.openRawFile();
    ImageSource src = ImageSource.create(is, null);
    PixelMap map = src.createPixelmap(null);

    Image image = new Image(this);
    image.setWidth(LayoutConfig.MATCH_PARENT);
    image.setHeight(LayoutConfig.MATCH_PARENT);
    image.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
    image.setPixelMap(map);

    ((DirectionalLayout)findComponentById(
        ResourceTable.Id_dir)).addComponent(image);
}
catch (IOException exception) {
    exception.printStackTrace();
}

例程:ImageFile

...\ImageFile\entry\src\main\resources\rawfile\image.jpg

...\ImageFile\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:id="$+id:dir"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical"
    ohos:background_element="#000000">

</DirectionalLayout>

...\ImageFile\entry\src\main\java\com\minwei\imagefile\slice\MainAbilitySlice.java

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        ...
        ResourceManager manager = getResourceManager();
        RawFileEntry entry = manager.getRawFileEntry(
            "resources/rawfile/image.jpg");

        try {
            InputStream is = entry.openRawFile();
            ImageSource src = ImageSource.create(is, null);
            PixelMap map = src.createPixelmap(null);

            Image image = new Image(this);
            image.setWidth(LayoutConfig.MATCH_PARENT);
            image.setHeight(LayoutConfig.MATCH_PARENT);
            image.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
            image.setPixelMap(map);

            ((DirectionalLayout)findComponentById(
                ResourceTable.Id_dir)).addComponent(image);
        }
        catch (IOException exception) {
            exception.printStackTrace();
        }
    }
    ...
}

运行效果如下图所示:

3 偏好数据库

3.1 获取偏好数据库

DatabaseHelper databaseHelper =
    new DatabaseHelper(getApplicationContext());
Preferences preferences =
    databaseHelper.getPreferences(preferencesFile);

3.2 实现观察者接口

class CounterObserver implements PreferencesObserver {
    private String counterKey;
    private Text txtObserver;

    public CounterObserver(String key, Text txtObserver) {
        this.counterKey = key;
        this.txtObserver = txtObserver;
    }

    @Override
    public void onChange(Preferences preferences, String s) {
        if (s.equals(counterKey))
            txtObserver.setText(
                String.valueOf(preferences.getInt(s, 0)));
    }
}

3.3 注册观察者对象

CounterObserver counterObserver = new CounterObserver(counterKey,
    (Text)findComponentById(ResourceTable.Id_txtObserver));
preferences.registerObserver(counterObserver);

3.4 读取偏好数据库

preferences.getInt(counterKey, 0);

3.5 保存偏好数据库

preferences.putInt(counterKey, counter);
preferences.flushSync();

3.6 注销观察者对象

preferences.unregisterObserver(counterObserver);

3.7 删除偏好库文件

databaseHelper.deletePreferences(preferencesFile);

例程:Preferences

...\Preferences\entry\src\main\resources\base\layout\ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical"
    ohos:background_element="#000000">

    <TableLayout
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:row_count="2"
        ohos:column_count="2">

        <Text
            ohos:id="$+id:txtCounter"
            ohos:height="60vp"
            ohos:width="100vp"
            ohos:text_size="50fp"
            ohos:text_color="#ffffff"
            ohos:text_alignment="center"
            />

        <Text
            ohos:id="$+id:txtObserver"
            ohos:height="60vp"
            ohos:width="100vp"
            ohos:left_margin="25vp"
            ohos:text_size="50fp"
            ohos:text_color="#ffffff"
            ohos:text_alignment="center"
            />

        <Button
            ohos:id="$+id:btnAdd"
            ohos:height="40vp"
            ohos:width="100vp"
            ohos:top_margin="15vp"
            ohos:background_element="#00a2e8"
            ohos:text="增加"
            ohos:text_size="20fp"
            ohos:text_color="#ffffff"
            />

        <Button
            ohos:id="$+id:btnDelete"
            ohos:height="40vp"
            ohos:width="100vp"
            ohos:top_margin="15vp"
            ohos:left_margin="25vp"
            ohos:background_element="#ff7f27"
            ohos:text="删除"
            ohos:text_size="20fp"
            ohos:text_color="#ffffff"
            />

    </TableLayout>

</DirectionalLayout>

...\Preferences\entry\src\main\java\com\minwei\preferences\slice\MainAbilitySlice.java

class CounterObserver implements PreferencesObserver {
    private String counterKey;
    private Text txtObserver;

    public CounterObserver(String key, Text txtObserver) {
        this.counterKey = key;
        this.txtObserver = txtObserver;
    }

    @Override
    public void onChange(Preferences preferences, String s) {
        if (s.equals(counterKey))
            txtObserver.setText(
                String.valueOf(preferences.getInt(s, 0)));
    }
}

public class MainAbilitySlice extends AbilitySlice {
    private final String preferencesFile = "MyPreferences";
    private final String counterKey = "Counter";

    private DatabaseHelper databaseHelper;
    private Preferences preferences;
    private CounterObserver counterObserver;
    private Text txtCounter;

    @Override
    public void onStart(Intent intent) {
        ...
        databaseHelper = new DatabaseHelper(getApplicationContext());
        preferences = databaseHelper.getPreferences(preferencesFile);
        counterObserver = new CounterObserver(counterKey,
            (Text)findComponentById(ResourceTable.Id_txtObserver));
        preferences.registerObserver(counterObserver);

        txtCounter = (Text)findComponentById(
            ResourceTable.Id_txtCounter);
        txtCounter.setText(String.valueOf(readCounter()));

        findComponentById(ResourceTable.Id_btnAdd)
            .setClickedListener(new ClickedListener() {
                @Override
                public void onClick(Component component) {
                    int counter = Integer.valueOf(
                        txtCounter.getText()).intValue();
                    ++counter;
                    txtCounter.setText(String.valueOf(counter));
                    saveCounter(counter);
                }
            });

        findComponentById(ResourceTable.Id_btnDelete)
            .setClickedListener(new ClickedListener() {
                @Override
                public void onClick(Component component) {
                    databaseHelper.deletePreferences(preferencesFile);
                }
            });
    }
    ...
    @Override
    public void onStop() {
        preferences.unregisterObserver(counterObserver);
    }

    private int readCounter() {
        return preferences.getInt(counterKey, 0);
    }

    private void saveCounter(int counter) {
        preferences.putInt(counterKey, counter);
        preferences.flushSync();
    }
}

运行效果如下图所示:

更多精彩,敬请期待……


达内集团C++教学部 2021年9月20日