如何逐行阅读文本文件?

时间:2017-05-26 15:21:25

标签: android arraylist

我的目标是能够将我的应用程序中的高分保存到我使用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();

    }



}

2 个答案:

答案 0 :(得分:1)

使用BufferedReader逐行读取并立即将它们放入ArrayList中。

答案 1 :(得分:0)

为了让您的生活更轻松,最好使用(1)BufferedReader::readline()方法或(2)Scanner::nextLine()方法。并将每行添加到for循环中的List<String>

一个简单的例子:

List<String> lines = new ArrayList<>();
String curLine = null;

BufferedReader reader = new BufferedReader(new FileReader("storetext.txt"));
while ((curLine = reader.readLine()) != null) {
  lines.add(curLine);
}
相关问题