1

可能重复:
android 从文本文件中读取

所以我需要加载文本,但我不知道如何:( 为了保存文本,我正在这样做

File logFile = new File("sdcard/data/agenda.file");
if (!logFile.exists())
{
    try
    {
        logFile.createNewFile();
    } 
    catch (IOException e)
    {

        e.printStackTrace();
    }
}
try
{
    //BufferedWriter for performance, true to set append to file flag
    BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
    buf.append(editText1.getText());
    buf.newLine();
    buf.close();
}
catch (IOException e)
{
    e.printStackTrace();
}

那么,如何通过点击按钮将其加载回来?

4

3 回答 3

2

要读取文件的内容,例如 *.txt - 这样做...

private String GetPhoneAddress() {
    File file = new File(Environment.getExternalStorageDirectory() + "/reklama/tck.txt");
    if (!file.exists()){
        String line = "Need to add smth";
        return line;
    }
    String line = null;
    //Read text from file
    //StringBuilder text = new StringBuilder();
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        line = br.readLine(); 
        }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }
    return line;
}

然后,从 activite 到设置为 textview - 只是做类似的事情

final TextView tvphone = (TextView) findViewById(R.id.saved_phone);
    String saved_phone = GetPhoneAddress();
    if (saved_phone.length()>0){
       tvphone.setText(saved_phone);
    }
于 2012-09-30T19:59:07.017 回答
1

此函数将读取您的整个文件,并将其设置TextView为文本参数,如果这是您想要的。您的代码正在尝试将TextViews内容写入文件,而不是读取它。

public void loadToTextView(TextView textView) throws Exception
{
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(path, "filename.file");
    textView.setText(new Scanner(file).useDelimiter("\\Z").next());
}

小心,你需要处理Exception这个函数可能抛出的 , 。

于 2012-09-30T19:32:21.237 回答
1

此方法会将每一行读入一个StringBuffer.

然后只需调用setText(contentsOfFile)您的TextView.

BufferedReader fileReader = new BufferedReader(new FileReader("/mnt/sdcard/agenda.file"));

StringBuilder strBuilder = new StringBuilder();

String line;
while((line = fileReader.readLine()) != null)
{
    strBuilder.append(line);
}

fileReader.close();

strBuilder.trimToSize();

String contentsOfFile = strBuilder.toString();
于 2012-09-30T19:42:14.210 回答