![](/img/trans.png)
[英]How to read strings off of .txt file and sort them into an ArrayList based on the number of occurrences?
[英]How to sort strings from txt file and post them to textview item
我正在從txt文件讀取一些string.TextView顯示給我:“ score = 10”“ score = 1”“ score = 5”“ score = 11”我想像這樣進行排序:TextView顯示:“ score = 1”“ score = 5“”得分= 10“”得分= 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();
}
刪除文本文件中每一行的“ score =”部分,然后針對每一行檢查其余內容是否為有效數字-如果是這樣,請將其作為整數存儲在集合中。 閱讀完文本文件后,您可以對集合進行排序,並以所需的方式在TextView中使用數據。
您可以執行以下Scanner Reader = new Scanner(fileName); 在for循環中,使用Reader.nextInt()函數讀取所有整數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.