如何将文本从文件加载到textview

时间:2012-09-30 19:16:29

标签: android file-io textview

  

可能重复:
  android reading from a text file

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

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();
}

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

3 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分: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

答案 2 :(得分: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();