Search code examples
javaandroidarraysfileinputstream

Reading a txt-file and store it in simple array


I had a bit problems with the issue to load files from an existing txt-file in Android.

The plan is, to read the txt file and store the readed string into a string array on appstart.

The save in txt file code:

    private void safeScore() {
            File myDir = new File(Environment.getExternalStorageDirectory().toString()
                    + directoryPath);
            myDir.mkdir();

            try {
                File myFile = new File(Environment.getExternalStorageDirectory().getPath() + directoryPath +"/Spieler.txt");
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

                for (int i = 0; i < Highscore.nameHS.length; i++)
                {
                    myOutWriter.write(Highscore.nameHS[i] + ";");
                }

                myOutWriter.close();
                fOut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
}

Now I planed on appstart that the values of this txt should stored back into the array. Simple said - the opposit way.

The separator for the split command is the ";".

The String Array nameHS of the class Highscore is a normal array. No arraylist.

Maybe someone could help me to store the values back into the array.

Greetings,

Sven


Solution

  • BufferedReader in = new BufferedReader(new FileReader("Spieler.txt"));
    String s1 = new String();
    while((s1 = in.readLine()) != null) {
        Highscore.nameHS[i++];
    }
    in.close(); 
    

    Maybe you can try it in this direction, if I understand what you want to do