Use the properties file in Android to save program settings

Source: Internet
Author: User

 

The properties file is often used in Java and parsed by using the properties class. Here, the benefits of using the properties file are not stated, and we mainly discuss how to use the properties file in Android!

 

Method 1: Because the properties file is finally read through the stream file, it is natural that we want to put the file into the assets folder or raw folder.

For example, we have a file --> test. properties. If it is placed in the assets folder, you can open it as follows:

Properties pro = new properties ();

Inputstream is = context. getassets (). Open ("test. properties ");

Pro. Load (is );

You can open the raw folder as follows:

Inputstream is = context. getresources (). openrawresource (R. Raw. test );

 

However, sometimes we don't want to get the context of Android, but load the properties file like the standard method in Java. How can we use it? See Method 2:

 

 

Method 2: loading without context! [Recommended Methods]

Properties pro = new properties ();

Pro. Load (fileload. Class. getresourceasstream ("test. properties "));

Fileload is the class name of the class where the loading method is located. The path where test. properties is stored is the same as fileload. java.

 

However, in Android, when we package and generate an APK and put it on a real mobile phone, you will not find test. the properties file should not be surprised. The resource files in android can only be stored in the assets or res sub-directories. The resource files in the package will be lost after compilation! So is our second method unusable? Of course not. After experiment, we found that you can still reference the file by placing the file in the assets folder and entering the absolute path of the file in the input path.

Code: Pro. Load (fileload. Class. getresourceasstream ("/assets/test. properties "));

 

Note: The root path of the Project path is "/"

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.