简体   繁体   中英

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

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

If others had the same Problem. Below you find my solution using the code snippet of elvirt:

        try
        {
            BufferedReader in = new BufferedReader(new FileReader(Environment.getExternalStorageDirectory().toString() + directoryPath + "/Spieler.txt"));
            String s1 = new String();

            int i = 0;

            while((s1 = in.readLine()) != null) {

                //Toast.makeText(getApplicationContext(), "TextFile wurde geladen!" + " Wert: " + s1, Toast.LENGTH_SHORT).show();
                Highscore.nameHS[i++] = s1;

            }
            in.close();
        }
        catch( IOException e )
        {
            Toast.makeText(getApplicationContext(), "Fehler beim Laden der Highscore-Spieler Datei!", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM