有没有更简单的方法来解析Java中的Android?
问题描述:
我很难执行什么应该是一个简单的任务。比方说,我有一个规定的文本文件:有没有更简单的方法来解析Java中的Android?
a = b
我想我的程序读取该文件,并输出“B”,只要用户输入“A”。在Python或C++中,我可以在大约7行或更少的行中完成此操作。
但是,我很难找到一种简单的方法在Android上执行此操作。例如,我在SO上找到的一个样本在6个文件中有近900行。
有没有一种简单的方法来解析文件并在Android上返回一个我失踪的变量?
答
只要你满意的属性文件中使用的a = b
格式,你得到的方式99%到你的目标与含有
Properties properties = new Properties();
try {
properties.load(new FileInputStream(filename));
} catch (IOException e) {
// the file is missing or is not in 'a = b' format
}
的,得到了具有可变key
的字符串"a"
,如果文件包含行a = b
,则properties.getProperty (key)
的结果将等于"b"
。我非常肯定你需要比C++更多的功能来从文件加载映射并处理所有转义和字符编码问题。
如果属性在文本文件中保存名为mappings.properties在资产您的Android项目的文件夹,而不是在用户的文件系统,那么你得到这样的:
final AssetManager am = getResources().getAssets();
final Properties properties = new Properties();
try {
properties.load(am.open("mappings.properties"));
} catch (IOException e) {
// the file is missing or is not in 'a = b' format
}
如果在编辑框中输入了'a',则该下一位从android tutorial借用以显示其中包含'b'的吐司消息。也许这就是你从哪里得到你的线数,因为设置一个带有XML文件的图形用户界面并且在Java中添加监听器与其他语言相比是相当冗长的。这是由于Java和XML语法,而不是虚拟机。
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
Toast.makeText(YourOuterViewClass.this,
properties.getProperty(edittext.getText().toString()),
Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
答
你绝对不需要数百行代码来实现这一点。它可以在几行完成。我不知道你在看什么样的例子,但它们可能比你所描述的要多。
答
BufferedReader r = new BufferedReader(new FileReader(filename));
string s;
while(s = r.readLine()) {
//Oh hey, I got a line out of the file.
//In three lines of code.
//So what's all this Android-bashing about?
}
葛底斯堡的地址实际上很短,因为它是~20行,包含80个字符列和一个等宽字体。 – 2011-01-25 20:39:05
此外,我想这与900 LOC的SO应答。我似乎无法找到它... – 2011-01-25 20:44:12