HarmonyOS 파일 스토리지

13739 단어


여러분, 안녕하세요,
이번 글에서는 Huawei에서 개발한 새로운 운영체제인 HarmonyOS로 스마트워치용 파일 스토리지를 활용하여 애플리케이션을 개발하는 방법에 대해 이야기하고, 몇 가지 샘플 코드를 공유해 보도록 하겠습니다.
먼저 HarmonyOS가 무엇인지, 언제 출시되었는지 궁금하시다면 아래 링크를 클릭하시면 HarmonyOS에 대한 중요한 내용을 보실 수 있습니다.
What is File Storage?
File Storage, one of the services offered by HarmonyOS to developers, is used to store files on the device.
Thanks to this feature, you can store files on the HarmonyOS devices, list the files you have stored, make changes on them, edit and delete the content according to the file type.
In this article, I will talk about file storage for Lite Wearable devices. First of all, I will store a file on the Lite Wearable device and read the data from this file. Then, I will give a new output to the user by comparing this file with the data I received from the user. For this, I will create a .txt file on the Lite Wearable device and write the data I need into it.
If you do not need file storage, you can save the data directly to the device’s memory with the data storage feature. You can visit this link to learn more about data storage.

Development Steps
1. Creating a HarmonyOS Project
To create a new HarmonyOS project, firstly, you must have DevEco Studio installed on your computer and have a developer account.
You need to create your application through the developer console, obtain an application-specific certificate and add this certificate to the project you created in DevEco Studio. You can access the Medium article which describing these steps from the link below. With this article, you can learn and apply the steps you need to complete before starting the project.

2. Create a Directory
You can save a file directly to the directory on the device, or you may need a specific directory to save more than one file. In this case, you must first create a new directory that will meet your needs.
For this, you need to use the file.mkdir method. First, in this method, you need to define the directory you want to create with the “uri” variable. After making the necessary definition, you can check whether the operation is successful by calling the success and fail methods, printing a log within these methods, or showing information messages to the user.
The code block required to create a new directory should be as follows. As seen in the example, you can create a new directory with this short code block, then save the files in this directory and list the files you have saved.
createNewDirectory() {
        file.mkdir({
            uri: 'internal://app/newDirectory',
            success: function () {
                console.log('New directory was created successfully.');
            },
            fail: function (data, code) {
                console.error('Failed to create new directory. Error code: ' + code + ', Data: ' + data);
            },
        });
    },

3. Delete a Directory
If you are not using the directory you created before, or if you want to delete it, you need to use the file.rmdir method.
You need to define the directory you want to delete with the “uri” variable. After making the necessary definition, you can check whether the operation is successful by calling the success and fail methods, printing a log within these methods, or showing information messages to the user.
The code block required to delete an exist directory should be as follows. As seen in the example, you can delete an exist directory with this short code block.

deleteDirectory() {
        file.rmdir({
            uri: 'internal://app/newDirectory',
            recursive: true,
            success: function() {
                console.log('Directory deleted successfully.');
            },
            fail: function(data, code) {
                console.error('An error occurred while deleting the directory. Error code: ' + code + ', data: ' + data);
            },
        });
    },

4. Write Text
The file.writeText method should be used to create a .txt file and write some data in this file.
The most important point to note here is that to write to a file, that file does not need to exist. Thanks to the file.writeText method, a file with the name you specify will be automatically created at the specified location and the string you have given as a parameter will be written into this file.
To summarize, we only defined a uri value when creating a new directory.
In order to write to the file, we need to define a text value in addition to this URI value. After this two-line code, you can check whether the operation is successful by calling the success and fail methods as always, printing a log within these methods or showing information messages to the user.

writeText() {
        file.writeText({
            uri: 'internal://app/newDirectory/test.txt',
            text: 'Text that just for test.',
            success: function () {
                console.log('Writing completed successfully.');
            },
            fail: function (data, code) {
                console.error('An error occurred while typing. Error code: ' + code + ', data: ' + data);
            },
        });
    },

5. Get File Information
Use the file.get method to access information such as the URI, length, last modified date, and type of file of any file you have saved before.

getFile() {
        file.get({
            uri: 'internal://app/newDirectory/test.txt',
            success: function (data) {
                console.log("Successfull. URI : " + data.uri + "Length : " + data.length 
                      + "Last Modified Time : " + data.lastModifiedTime + " Type : " + data.type);
            },
            fail: function (data, code) {
                console.error('Error code: ' + code + ', data: ' + data);
            },
        });
    },

6. Read File
You can use the file.readText method to read the files that you have created and written data in before. With this method, you can read the content of a text file, display it to the user and process this data. First, define the uri of the relevant file. After than, you can check whether the operation is successful by calling the success and fail methods as always, printing a log within these methods or showing information messages to the user.

readText() {
        file.readText({
            uri: 'internal://app/newDirectory/test.txt',
            success: function (data) {
                console.log('Reading successful. Data : ' + data.text);
            },
            fail: function (data, code) {
                console.error('Read failed. Error code: ' + code + ', data: ' + data);
            },
        });
    },

7. Copy File
This is easy to do when you need a copy of an existing file. For this, it will be sufficient to use the file.copy method and give the source file URI and destination file URI as parameters. The only important thing to note is that the source file URI and name and the destination URI and name are not the same. The code block required for file copying is as follows.

copyFile() {
        file.copy({
            srcUri: 'internal://app/newDirectory/test.txt',
            dstUri: 'internal://app/newDirectory/copyTest.txt',
            success: function (uri) {
                console.log('File was copied successfully.');
            },
            fail: function (data, code) {
                console.error('An error occurred while copying the file. Error code: ' + code + ', data: ' + data);
            },
        });
    },

8. Move File
The file.move method is used to change the location of an existing file. First, give the source file URI and the URI you want to be moved as parameters to this method. After than, you can check whether the operation is successful by calling the success and fail methods as always, printing a log within these methods or showing information messages to the user.

moveFile() {
        file.move({
            srcUri: 'internal://app/newDirectory/test.txt',
            dstUri: 'internal://app/oldDirectory/test.txt',
            success: function (uri) {
                console.log('call move success');
            },
            fail: function (data, code) {
                console.error('call fail callback fail, code: ' + code + ', data: ' + data);
            },
        });
    },

9. Listing Files
The file.list method is used to list the files you have saved before and all other existing files and to learn the details of these files (URI, last modified date, size and file type, etc.). Thanks to this method, if the listing is successful, you can create a for loop in the success method and see the list of all files at the relevant address. The sample code should be as follows.

listFile() {
        file.list({
            uri: 'internal://app/newDirectory',
            success: function (data) {
                console.log('Internal File list:' + 'Uri: ' + data.fileList[0].uri + ' LastModifiedTime: ' + data.fileList[0].lastModifiedTime +
                ' Length: ' + data.fileList[0].length + ' Type: ' + data.fileList[0].type);
            },
            fail: function (data, code) {
                console.error('call fail callback fail, code: ' + code + ', data: ' + data);
            },
        });
    },

10. Delete File
Finally, let’s see how to delete a file we created. As you can see in the examples above, with the HarmonyOS JS API, all operations can be performed successfully without writing very long and complex codes. The same goes for file deletion. You can delete a file by giving the URI of the file you want to be deleted to the file.delete method and calling the success and fail methods.

deleteFile() {
        file.delete({
            uri: 'internal://app/newDirectory/test.txt',
            success: function () {
                console.log('call delete success.');
            },
            fail: function (data, code) {
                console.error('call fail callback fail, code: ' + code + ', data: ' + data);
            },
        });
    },

Tips & Tricks

  • The URI value must be a maximum of 128 characters and must not contain any special characters.

  • If there are characters such as quotation marks in the text, the system will misunderstand this and the writing will not be successful because of the text is split.

  • Some important error codes and their explanations are as follows

202 : Invalid Parameter
300 : I/O Error
301 : Directory or File Not Founded
References
Reference
Reference

좋은 웹페이지 즐겨찾기