【问题标题】:Read Input Text File and Compare (Android)读取输入文本文件并比较 (Android)
【发布时间】:2013-10-02 03:41:03
【问题描述】:

我有一个名为 params.txt 的文本文件,其中包括:

3
WENSY WENDY
PING PING
CHLOE CHLOE

我的问题是,如何读取这些输入并在一行中比较两个字符串?比较 Wensy 和 Wendy 等等..

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);           
        }
    });


    }


}

我可以将输入文本保存在字符串变量中吗?或者还有另一种简单的方法可以做到这一点?谢谢你:))

【问题讨论】:

  • @newuser 代码已添加。我不知道如何比较这两个字符串。

标签: java android data-access


【解决方案1】:

试试看,split()

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

【讨论】:

    【解决方案2】:

    您可以阅读答案here 以了解如何逐行读取文件。

    然后要比较每一行的两个部分,您可以通过这样做将它们分开:

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

    然后您可以使用parts[0]parts[1] 比较每个部分。 示例:

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

    【讨论】:

      【解决方案3】:

      在你的 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); 进行比较。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-15
        • 1970-01-01
        相关资源
        最近更新 更多