简体   繁体   中英

Android FileNotFoundException

I ported a Java Application to Android and everything is working fine, except that the App isn't able to load a .csv-file on my phone. It alway gives me the FileNotFoundException. Could anyone please help me? Any help is appreciated. Here is the buggy part of the code:

private String path = Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/Autoliste.csv";

public Auto[] lesenAutos() {
    int size = 0;
    try {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String line = reader.readLine();
        while (line != null) {
            size++;
            line = reader.readLine();
        }
        if (size == 0)
            System.out.println("Datei ist leer");
        reader.close();
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
    } catch (IOException e) {
        System.out.println("Error reading file");
    } catch (IndexOutOfBoundsException e) {
        System.out.println("Ungültige Zeichen vorhanden");
    }

    Auto[] arr = new Auto[size];
    int i = 0;
    try {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String zeile = reader.readLine();
        while (zeile != null) {
            arr[i] = new Auto();
            arr[i].setAuto(zeile);
            i++;
            zeile = reader.readLine();
        }
        reader.close();
    } catch (FileNotFoundException e) {
        System.out.println("Datei nicht gefunden");
    } catch (IOException e) {
        System.out.println("Lesefehler in Datei");
    }
    return arr;
}

Thanks, Tom.

probably you are missing to add the package name of your application with context.getPackageName()

private String path = Environment.getExternalStorageDirectory().getPath() + context.getPackageName() +  "/Autoliste.csv";

and be sure to have into your AndroidManifest.xml defined the next permission!:)

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

I just had this error, and I finally realized that when I changed the file I was using in my app, I forgot to add '.csv' to the end of the new file name. As soon as I added that, the error was gone. Make sure to include the file type! The devil is in the details. I wouldn't have added this answer, but I figured some novice similar to me could make the same mistake down the road.

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