简体   繁体   中英

FileInputStream and FileOutputStream

I created a .txt file and want to save the data I type into a textbox into the file. And if I click on a button I want to load the data I saved out of the file. I have the code for both, but it does not work, I hope you can help me if I have some mistakes :)

Load out of file:

public void Liste() throws FileNotFoundException {
    try {
        FileInputStream instream = openFileInput(Environment.getDataDirectory()
                + "/assets/bmiwerte.txt");
        if (instream != null) {
            InputStreamReader inputreader = new InputStreamReader(instream);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line, line1 = "";
            try {
                while ((line = buffreader.readLine()) != null)
                    line1 += line;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        String error = "Fehlermeldung!!!";
        error = e.getMessage();
    }
}

Save into file:

public void SaveList(View view) {
    //Pfad, im privaten Speicherbereich Environment.getDataDirectory();
    File file = new File(Environment.getDataDirectory() + "/assets/bmiwerte.txt");
    try {
        OutputStreamWriter fdg = new OutputStreamWriter(new FileOutputStream(file, true));
        fdg.write("" + this.weight);
        fdg.close();

        OutputStreamWriter asdf = new OutputStreamWriter(new FileOutputStream(file, true));
        asdf.write("" + this.height);
        asdf.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Intent intent = new Intent(this, MyList.class);
    startActivity(intent);
}

Add permissions to AndroidManifest.xml file:

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

Edt: Also use Environment.getExternalStorageDirectory() instead Environment.getDataDirectory() its ReadOnly .

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