-1

你好,所有关于 android 外部数据存储的教程都让我抓狂

我有一个 OnOptionsCreatemenu 有 2 个按钮“保存”和“加载”保存工作正常但加载不在这里是我的代码它不会让我在代码中注释掉我如何让它让我将它保存在我自己的目录中?...iv 阅读每一个关于保存到 ext 存储的教程 5 次 ......我只是愚蠢地得到它!(请不要链接)然后请把它变成一个新的教程,因为这将是最简单的 android ext 数据存储故障,即使像我这样的智障黑猩猩也会理解

这都是一段代码......不知道为什么代码显示在 2 个代码框中???

ps对不起这是我的第一次......很容易;)

私人无效保存(){

    String saveLine = ((EditText)
            findViewById(R.id.captain)).getText().toString().trim();

    File sdcard = Environment.getExternalStorageDirectory();

    File file = new File(sdcard,"/myfile.txt");

    try {

        FileWriter fw = new FileWriter(file);

        BufferedWriter bw = new BufferedWriter(fw);

        bw.write(saveLine);

        bw.close();
        Toast.makeText(getApplicationContext(),"File saved!",Toast.LENGTH_LONG).show();
    } catch (IOException e) {

        Toast.makeText(getApplicationContext(),"Error writing file!",Toast.LENGTH_LONG).show();

    }
    {

//这里说我需要放一个变量?为什么它不让我像 save() 函数一样使用它????

    private void load() {

      //  ensure();

        sdcard = Environment.getExternalStorageDirectory();

        File file1 = new File(sdcard,"/myfile.txt");


        try {

            BufferedReader br = new BufferedReader(new FileReader(file1));

           String loadline;

            if ((loadline = br.readLine()) != null) {

                String content=loadline.toString();

                ((EditText)
                        findViewById(R.id.captain)).setText(content);



            }

            br.close();

        }

        catch (IOException e) {

            Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();

        }

    }
4

1 回答 1

0

您似乎在读取文件时遇到问题,对吧?从 SD 卡读取文件并将其设置到EditText这里是代码:

private void load(){

    File sdcard = Environment.getExternalStorageDirectory();

    //Get the text file
    File file = new File(sdcard,"myfile.txt");

    //Read text from file
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
    }
    catch (IOException e) {
        //You'll need to add proper error handling here
        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
    }

    //Find the view by its id
    EditText ed = (EditText)findViewById(R.id.captain);

    //Set the text
    ed.setText(text);
}

确切来源:如何从 Android 的 SD 卡中读取文本文件?

希望这有助于其他评论。

于 2013-07-21T01:31:46.473 回答