我的目標是能夠將我的應用程序保存到使用FileOutputStream創建的文本文件中的高分數。然後我希望能夠從文件讀取並將每行放入數組列表項。在使用InputStreamReader時,我可以將文本文件中的所有文本行加載到變量s中。我現在的問題是我想從文本文件中取出每行並將其保存到數組列表項中。我將如何實現這一目標?如何逐行讀取文本文件?
Example string variables for high scores:
String myStr = "Ryan 150 hard \n";
String myStr2 = "Andrew 200 Medium \n";
public void saveClick(){
try{
//String myNum = Integer.toString(life);
FileOutputStream fOut = openFileOutput("storetext.txt", Context.MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fOut);
outputWriter.write(myStr);
outputWriter.write(myStr2);
outputWriter.close();
/*OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.write(life);
out.close();*/
Toast.makeText(getApplicationContext(), "Save Successful", Toast.LENGTH_LONG).show();
}
catch(Throwable t){
Toast.makeText(getApplicationContext(), "Save Unsuccessful", Toast.LENGTH_LONG).show();
}
}
public void readFileInEditor(){
try{
FileInputStream fileIn = openFileInput("storetext.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
char [] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0){
//char to string conversion
String readString = String.copyValueOf(inputBuffer,0,charRead);
s += readString;
}
InputRead.close();
Toast.makeText(getApplicationContext(), "New Text: " + s , Toast.LENGTH_LONG).show();
//myText.setText("" + s);
try{
//life = Integer.parseInt(s);
//Toast.makeText(getApplicationContext(), "My Num: " + life , Toast.LENGTH_LONG).show();
}
catch(NumberFormatException e){
//Toast.makeText(getApplicationContext(), "Could not get number" + life , Toast.LENGTH_LONG).show();
}
}
catch(java.io.FileNotFoundException e){
//have not created it yet
}
catch(Throwable t){
Toast.makeText(getApplicationContext(), "Exception: "+t.toString(), Toast.LENGTH_LONG).show();
}
}
感謝您的快速響應。如果我想使用BufferedReader方法,它將如何尋找for循環,我對Java很新穎? –
@RyanWing我已經在回答中添加了一些示例代碼 – volatilevar
我已經實現了您提供的代碼以及添加的代碼。在包含代碼時我保留了FileInputStream和DataInputStream,並且僅使用2個字符串變量作爲測試。當我Toast出結果我得到的第二行形式的文本文件兩次,而不是第一行的文本文件,然後第二行的文本文件。關於爲什麼會發生的任何想法? –