Android - 从文件读取和写入

时间:2017-05-27 15:07:56

标签: android

我是Android编程的初学者。 我正在尝试为用户提供输入某些信息的表单。 我想将该信息写入文件,然后从文件中读取并在TextView中显示。目前,我读到的是null。你能帮我解决这个问题吗? 代码就是这个:

submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // write
        StringBuilder s = new StringBuilder();
        s.append("Event name: " + editText1.getText() + "|");
        s.append("Date: " + editText2.getText() +  "|");
        s.append("Details: " + editText3.getText() + "|");

        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        File file= new File(extStorageDirectory, "config.txt");
        try {
            writeToFile(s.toString().getBytes(), file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // read from file and show in text view
        Context context = getApplicationContext();
        String filename = "config.txt";
        String str = readFromFile(context, filename);
        String first = "You have inputted: \n";
        first += str;
        textView.setText(first);

    }
});

写功能:

public static void writeToFile(byte[] data, File file) throws IOException {
    BufferedOutputStream bos = null;
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data);
    }
    finally {
        if (bos != null) {
            try {
                bos.flush ();
                bos.close ();
            }
            catch (Exception e) {
            }
        }
    }
}   

阅读功能:

public String readFromFile(Context context, String filename) {
    try {
        FileInputStream fis = context.openFileInput(filename);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        return sb.toString();
    } catch (FileNotFoundException e) {
        return "";
    } catch (UnsupportedEncodingException e) {
        return "";
    } catch (IOException e) {
        return "";
    }
}

2 个答案:

答案 0 :(得分:0)

如果我没有遗漏您写入文件的内容

String extStorageDirectory = 
Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");

但你从

读到
FileInputStream fis = context.openFileInput(filename);

后者在应用程序基目录中使用dir,而输出则转到外部strage目录的基目录。

为什么不使用context.openFileOutput()代替getExternalStorageDirectory()

如果文件应存储在外部,请尝试以下操作:创建File对象的方式保持不变。请使用FileOutputStream fos = new FileOutputStream(file);而不是FileInputStream(写作)。请记住在清单中设置适当的权限。在哪些情况下他们是必要的,请参阅Android文档。

答案 1 :(得分:0)

Edittext的getText()方法返回editable。首先,您应该使用toString()函数将其转换为字符串。并检查您是否已授予WRITE_EXTERNAL_STORAGE权限。