If the properties file is read through the stream file, you need to put the file into the assets folder or raw folder. for example, we have a file named test. properties:
Java code www.2cto.com
Properties pro = new Properties ();
InputStream is = context. getAssets (). open ("test. properties ");
Pro. load (is );
You can open the raw folder as follows:
Java code
InputStream is = context. getResources (). openRawResource (R. raw. test );
Java code
Properties pro = new Properties ();
Pro. load (FileLoad. class. getResourceAsStream ("/assets/test. properties "));
Read/write functions are as follows:
[Java]
Import java. io. FileInputStream;
Import java. io. FileOutputStream;
Import java. util. Properties;
Public Properties loadConfig (Context context, String file ){
Properties properties = new Properties ();
Try {
FileInputStream s = new FileInputStream (file );
Properties. load (s );
} Catch (Exception e ){
E. printStackTrace ();
}
Return properties;
}
Public void saveConfig (Context context, String file, Properties properties ){
Try {
FileOutputStream s = new FileOutputStream (file, false );
Properties. store (s ,"");
} Catch (Exception e ){
E. printStackTrace ();
}
}
Orz, did you find anything? By the way, these two functions have nothing to do with Android ..
So they can also be used in other standard java programs.
In Android, compared to reading and writing strings only and parsing them themselves, or saving the configuration with xml,
Properties is simpler and more intuitive, because self-parsing requires a lot of code, and xml operations are far less convenient than Properties.
The usage is as follows:
Write Configuration:
Properties prop = new Properties ();
Prop. put ("prop1", "abc ");
Prop. put ("prop2", 1 );
Prop. put ("prop3", 3.14 );
SaveConfig (this, "/sdcard/config. dat", prop );
Read Configuration:
Properties prop = loadConfig (this, "/sdcard/config. dat ");
String prop1 = prop. get ("prop1 ");
Note: You can also use the openFileInput and openFileOutput methods of Context to read and write files.
At this time, the file will be saved under/data/package_name/files and handed over to the system for unified management.
When you use this method to read and write files, you cannot specify a specific path for the file.
In android, when we package and generate an apk and put it on a real mobile phone, you cannot 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 we can put the file into the assets folder, and enter the absolute path of the file in the input path to reference the file.