如何从文本文件中排序字符串并将其发布到textview项目

时间:2014-03-30 14:28:24

标签: java android sorting textview

我正在从txt文件中读取一些字符串.TextView向我显示:“得分= 10”“得分= 1”“得分= 5”“得分= 11” 我想对此进行排序:TextView显示:“score = 1”“score = 5”“score = 10”“score = 11” 我不知道如何排序这些字符串。这不是整数。 你可以帮我举个例子吗?或者你能看到我的代码吗?

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.wyniki);

    final TextView scores = (TextView) findViewById(R.id.textView4);
    final Button button5 = (Button) findViewById(R.id.button5);
    String saved_scores = readText();
    if (saved_scores.length()>0){
        scores.setText(saved_scores);}

    sort();

    button5.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {


             final File f = new File(Environment.getExternalStorageDirectory()+"/cos/Wynik.txt");
            if (f.exists()){
                f.delete(); 

                Toast.makeText(getApplicationContext(),"Deleted",Toast.LENGTH_SHORT).show();


                scores.setText(null);

            }
        }
    });


}

public String readText(){
     //this is your text
     StringBuilder text = new StringBuilder();
 try{

     final File f = new File(Environment.getExternalStorageDirectory()+"/cos/Wynik.txt");
     FileInputStream fileIS = new FileInputStream(f);
     BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
              String readString = "";
     //just reading each line and pass it on the debugger  
     while((readString = buf.readLine())!= null){
        Log.d("line: ", readString);
        text.append(readString + "\n");
               }
     buf.close();
  } catch (FileNotFoundException e) {

     e.printStackTrace();

  } catch (IOException e){

     e.printStackTrace();

  }
         return text.toString();

}

2 个答案:

答案 0 :(得分:0)

删除文本文件中每行的“score =”部分,并为每行检查剩余内容是否为有效数字 - 如果是,则将其作为整数存储在集合中。完成阅读文本文件后,您只需对集合进行排序,并以TextView中的任何方式使用数据。

答案 1 :(得分:0)

您可以执行以下操作 扫描仪读卡器=新扫描仪(fileName); 在for循环中,使用Reader.nextInt()函数读取所有整数。