.txt File aus dem Speicher des Smartphone lesen

werdas34

Bekanntes Mitglied
Hallo,

ich bin blutiger Anfäger was App-Programmierung angeht.

Ich versuche nun seit paar Stunden aus dem Verzeichnis des Smartphones eine txt Datei auszulesen. Aber dies funktioniert nicht.
Mein Ziel ist es die player.txt aus dem Ordner Documents zu lesen und dann in meine Liste zu laden.

Was dagegen funktioniert ist, wenn die txt Datei im AndroidStudio gespeichert ist.

Hier mal der letzte Stand:
Code:
 load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final File file = new File(Environment.getExternalStorageDirectory()
                        .getAbsolutePath(), "player.txt");

                String[] arr = loadFile(file);
                String text = arrayToString(arr);


            String parts[] = text.split(";");
            for (int i = 0; i < parts.length; i++){
                String name[] = parts[i].split(", ");
                playerList.add(new Player(name[0], name[1]));
            }
            }
        });

public static String[] loadFile(File file)
    {
        FileInputStream fis = null;
        try
        {
            fis = new FileInputStream(file);
        }
        catch (FileNotFoundException e) {e.printStackTrace();}
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);

        String test;
        int anzahl=0;
        try
        {
            while ((test=br.readLine()) != null)
            {
                anzahl++;
            }
        }
        catch (IOException e) {e.printStackTrace();}

        try
        {
            fis.getChannel().position(0);
        }
        catch (IOException e) {e.printStackTrace();}

        String[] array = new String[anzahl];

        String line;
        int i = 0;
        try
        {
            while((line=br.readLine())!=null)
            {
                array[i] = line;
                i++;
            }
        }
        catch (IOException e) {e.printStackTrace();}
        return array;
    }

    public static String arrayToString(String[] arr){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < arr.length; i++){
            sb.append(arr[i]);
        }
        return sb.toString();
    }

Habe auch die Permission gesetzt:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.schda.game">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        >

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Würde mich freuen wenn ihr mir helfen könntet.

Danke.
 

werdas34

Bekanntes Mitglied
Process: com.example.schda.game, PID: 1960
java.lang.NullPointerException: lock == null
at java.io.Reader.<init>(Reader.java:64)
at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
at java.io.InputStreamReader.<init>(InputStreamReader.java:57)
at com.example.schda.game.MainActivity.loadFile(MainActivity.java:248)
at com.example.schda.game.MainActivity$6.onClick(MainActivity.java:213)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
 

Robat

Top Contributor
Dann wird wahrscheinlich der Inputstream null sein. Prüf das mal mit einer Ausgabe (und am Besten schaust du gleich noch mal ob der Pfad zum File stimmt)
 

werdas34

Bekanntes Mitglied
9-16 21:10:36.550 14365-14365/com.example.schda.game W/System.err: java.io.FileNotFoundException: /storage/emulated/0/player.txt: open failed: ENOENT (No such file or directory)

Die Datei wird nicht gefunden.

Oder muss man die Datei besonders speichern?
Ich habe am Smartphone Eigene Dateien geöffnet und dann unter dem Ordner Documents die Datei erstellt.
 

Robat

Top Contributor
Das kommt drauf an. Du versuchst ja auf ein externes Speichermedium (SD-Karte o.ä) zu zugreifen .. gibt es das denn bei deinem Smartphone / liegt der Ordner "Eigene Dateien" auf der SD-Karte?
 

werdas34

Bekanntes Mitglied
Auf der SD-Karte liegt die Datei in keinem Ordner. Eigentlich war der Plan im internen Speicher auf die diese Datei zuzugreifen.
Kurz gesagt:
Ich habe diese Datei zweimal.
Einmal auf der SD Card in keinem Ordner.
Interner Speicher vom Smartphone im Ordner Documents.
 

werdas34

Bekanntes Mitglied

Danke, aber das bringt mir leider auch wenig, da die Datei aus mir unbekannten Gründen sich nicht öffnen lässt.
Habe auch schon mehrere Stackoverflow Beiträge durch gelesen, aber das funktioniert nicht so wies sollte.

Hier der letzte Stand des Fileopening Prozesses:
Java:
             //   File file = new File(Environment.getExternalStorageDirectory()
             //           .getAbsolutePath(), "player.txt");

             //   File file = new File(context.getExternalFilesDir() + "/" + "player.txt")

                File sdcard = Environment.getExternalStorageDirectory();
                File file = new File(sdcard,"player.txt");
                String[] arr = loadFile(file);
Ich bekomme eine FileNotFoundException.
 

mihe7

Top Contributor
Danke, aber das bringt mir leider auch wenig, da die Datei aus mir unbekannten Gründen sich nicht öffnen lässt.
...
Ich bekomme eine FileNotFoundException.
Na, dann schauen wir mal... Mach mal folgendes:
Java:
File sdcard = Environment.getExternalStorageDirectory();
Log.i(TAG, "Listing dir " + sdcard.toString());
for (String s : sdcard.list()) {
    Log.i(TAG, s);
}
File file = new File(sdcard,"player.txt");
String[] arr = loadFile(file);
Was steht im Logcat?
 

werdas34

Bekanntes Mitglied
09-17 18:37:01.240 16196-16196/com.example.schda.game D/ViewRootImpl: ViewPostImeInputStage processPointer 1
09-17 18:37:01.860 16196-16196/com.example.schda.game D/ViewRootImpl: ViewPostImeInputStage processPointer 0
09-17 18:37:02.010 16196-16196/com.example.schda.game D/ViewRootImpl: ViewPostImeInputStage processPointer 1
09-17 18:37:02.010 16196-16196/com.example.schda.game I/com.example.schda.game.MainActivity: Listing dir /storage/emulated/0
09-17 18:37:02.010 16196-16196/com.example.schda.game E/File: fail readDirectory() errno=13
09-17 18:37:02.010 16196-16196/com.example.schda.game D/AndroidRuntime: Shutting down VM
09-17 18:37:02.030 16196-16196/com.example.schda.game E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.schda.game, PID: 16196
java.lang.NullPointerException: Attempt to get length of null array
at com.example.schda.game.MainActivity$6.onClick(MainActivity.java:222)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Er erkennt offenbar die sd Karte nicht. Muss man da noch irgendwas einstellen?
Also ich habe eine sd Karte im Smartphone, daran liegts nicht.
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
M Firebase RealtimeDatabase - Daten aus Queries in CSV File speichern Android & Cross-Platform Mobile Apps 1
AndoridStudio Read-only file system Android & Cross-Platform Mobile Apps 5
M Unsupported class file major version 57 - Fehlermeldung bei Android Studio Android & Cross-Platform Mobile Apps 27
Soloeco Android Save File on external Storage Android & Cross-Platform Mobile Apps 3
S Android APK File Installationsfehler Android & Cross-Platform Mobile Apps 2
Flynn Text-File auf externe Speicherkarte schreiben Android & Cross-Platform Mobile Apps 1
B Android ListFragment parse xml from File Android & Cross-Platform Mobile Apps 1
B Android XML File ein lesen und menü erzeugen Android & Cross-Platform Mobile Apps 1
G In eier File schreiben Android & Cross-Platform Mobile Apps 8
M File der externen SD-Karte herausfinden Android & Cross-Platform Mobile Apps 3
G Port öffnen mit new SerialPort(new File... Android & Cross-Platform Mobile Apps 2
U Android Jar-File einbinden vs. externes Projekt Android & Cross-Platform Mobile Apps 7
K Java ME Export -> Invalid jar file ? Android & Cross-Platform Mobile Apps 9
F Eclipse JAD File erzeugen -- Problem Android & Cross-Platform Mobile Apps 10
M Daten aus Jad-file auslesen Android & Cross-Platform Mobile Apps 2
F Problem beim Erstellen der Jar File Android & Cross-Platform Mobile Apps 4
L Jar file auf Pda unter Windows Mobile ausführen Android & Cross-Platform Mobile Apps 2
P Erstellen einer Jar-File Android & Cross-Platform Mobile Apps 2
I Android SharedPreferences wenn App auf externem Speicher klappt nicht Android & Cross-Platform Mobile Apps 0
L Auflisten aller verfügbaren Speicher Android & Cross-Platform Mobile Apps 3
B Android App aus dem Speicher richtig beenden? Android & Cross-Platform Mobile Apps 6
K Dynamisches Menu saugt zuviel Speicher Android & Cross-Platform Mobile Apps 5
D Android System löscht benötigte Teile der App aus Speicher Android & Cross-Platform Mobile Apps 3
T Android Externen Speicher beschreiben Android & Cross-Platform Mobile Apps 3
M Android Android Programm mehr Speicher zuweisen Android & Cross-Platform Mobile Apps 4
M Android Studio - App auf dem Smartphone testen Android & Cross-Platform Mobile Apps 7
G App wird nach Installation auf Smartphone beendet Android & Cross-Platform Mobile Apps 1
A Benachrichtigung am Smartphone Android & Cross-Platform Mobile Apps 9
Fab1 Kommunikation Fernbedienung --> Smartphone Android & Cross-Platform Mobile Apps 5
L Android Spiel stockt auf Smartphone Android & Cross-Platform Mobile Apps 3
A Wie kann ich meine app auf meinem Smartphone zum laufen bekommen Android & Cross-Platform Mobile Apps 8
G Unterschiedliche Ausgabe in Emulator und auf Smartphone Android & Cross-Platform Mobile Apps 2
G unterschiedliches Verhalten beim Installieren des App auf dem Smartphone Android & Cross-Platform Mobile Apps 3
DaniSahne96 Problem beim Appdebuggen auf Smartphone Android & Cross-Platform Mobile Apps 3
D gpx-Datei von Smartphone auf Server uploaden Android & Cross-Platform Mobile Apps 4
S Entwicklung von Smartphone programmen ohne selber eins zu besitzen Android & Cross-Platform Mobile Apps 17
M Android Von Smartphone auf Daten von Server zugreifen Android & Cross-Platform Mobile Apps 2
H Smartphone (Front-)Kamera-Zugriff per Website Android & Cross-Platform Mobile Apps 6
E Fertiges Programm auf Smartphone zum laufen bringen. Android & Cross-Platform Mobile Apps 2

Ähnliche Java Themen

Neue Themen


Oben