android中Properties一般用的比较少,一般场景是用于获取系统配置键值对 System.getProperties()。其实它还有特殊功能。
解析指定格式的文件
(1)了解基本文件格式
我们可以看见android项目下会有properties文件,看下内容格式:
# # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. target=android-21
文件格式是目前是类似键值对的样式。
大概文件的格式,我们来看下它提供的接口能力。
(2)接口能力。
public synchronized void load(Reader reader) throws IOException { load0(new LineReader(reader)); } /** * Reads a property list (key and element pairs) from the input * byte stream. The input stream is in a simple line-oriented * format as specified in * {@link #load(java.io.Reader) load(Reader)} and is assumed to use * the ISO 8859-1 character encoding; that is each byte is one Latin1 * character. Characters not in Latin1, and certain special characters, * are represented in keys and elements using Unicode escapes as defined in * section 3.3 of * <cite>The Java™ Language Specification</cite>. * <p> * The specified stream remains open after this method returns. * * @param inStream the input stream. * @exception IOException if an error occurred when reading from the * input stream. * @throws IllegalArgumentException if the input stream contains a * malformed Unicode escape sequence. * @since 1.2 */ public synchronized void load(InputStream inStream) throws IOException { load0(new LineReader(inStream)); }
private void load0 (LineReader lr) throws IOException { ... String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf); String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf); put(key, value);
我们发现原来它还具有加载数据流的能力,这就意味着它可以支持指定流的解析了,解析详细过程咱不贴代码,有兴趣的可以看源码。大致过程就是在每一行中 找到 key的位置,以及value所对应的位置。然后内部键值对保存。
扫描二维码关注公众号,回复:
1160659 查看本文章