2011-01-25 117 views
-3

我很難執行什麼應該是一個簡單的任務。比方說,我有一個規定的文本文件:有沒有更簡單的方法來解析Java中的Android?

a = b 

我想我的程序讀取該文件,並輸出「B」,只要用戶輸入「A」。在Python或C++中,我可以在大約7行或更少的行中完成此操作。

但是,我很難找到一種簡單的方法在Android上執行此操作。例如,我在SO上找到的一個樣本在6個文件中有近900行。

有沒有一種簡單的方法來解析文件並在Android上返回一個我失蹤的變量?

+5

葛底斯堡的地址實際上很短,因爲它是~20行,包含80個字符列和一個等寬字體。 – 2011-01-25 20:39:05

+0

此外,我想這與900 LOC的SO應答。我似乎無法找到它... – 2011-01-25 20:44:12

回答

4

只要你滿意的屬性文件中使用的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; 
     } 
    }); 
2

你絕對不需要數百行代碼來實現這一點。它可以在幾行完成。我不知道你在看什麼樣的例子,但它們可能比你所描述的要多。

12
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? 
} 
相關問題