2013-10-02 57 views
0

我有這個文本文件名爲params.txt其中包括:讀取輸入的文本文件,比較(安卓)

3 
WENSY WENDY 
PING PING 
CHLOE CHLOE 

我的問題是,我怎麼能讀這個輸入並在一條線上的兩個字符串比較?比較Wensy和溫迪等..

Code:

public class MainActivity extends Activity { 

    InputStream is=null; 
    DataInputStream dis=null; 
    Resources myResources = null; 
    TextView tv=null; 
    String someText; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    Button verify = (Button) findViewById (R.id.verify); 
    myResources = this.getResources(); 
    tv = (TextView)findViewById(R.id.FileViewer); 
    is = myResources.openRawResource(R.raw.params); 
    dis = new DataInputStream(is); 
    someText = null; 

    verify.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      try{ 
       someText=dis.readLine(); 
       }catch(IOException ioe){ 
       someText ="Couldn't read the file"; 
       } 
       tv.setText(someText);   
     } 
    }); 


    } 


} 

我可以節省一個字符串變量輸入的文本?或者有另一個簡單的方法來做到這一點?謝謝:))

+1

你試過了什麼? – newuser

+0

@新增用戶代碼。我不知道如何比較這兩個字符串。 – pingboo23

回答

1

你可以閱讀答案here找出如何逐行讀取文件。

然後通過這樣做每一行的兩個部分可以單獨對其進行比較:

String[] parts = line.split(" "); 

然後你就可以比較使用parts[0]parts[1]每一個部分。 實施例:

if(parts[0].equals(parts[1])) { 
    doSomething(); 
} 
2

嘗試,split()

String[] splittedValues = someText.split(" "); 
if (splittedValues[0].equalsIgnoreCase(splittedValues[1])) 
    { 
     // do your process 
    } 
0

後您someText = dis.readLine();

String[] split = someText.split(" "); 
if (split[0].equals(split[1]){ 
    Log.i("MainActivity", "strings are equal"); 
}else{ 
    Log.i("MainActivity", "strings are not equal"); 
} 

將比較以查看字符串是否相等。否則,您可以使用String.compareTo(otherString);進行比較。