我的目标是能够将我的应用程序保存到使用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出结果我得到的第二行形式的文本文件两次,而不是第一行的文本文件,然后第二行的文本文件。关于为什么会发生的任何想法? –