文件存储

一、将数据存储到文件中

Context类中提供了一个openFileOutput()方法,可以将数据存储到指定的文件中。接受两个参数,第一个是文件名,第二个是文件的操作模式,主要有两种可选,MODE_PRIVATE和MODE_APPEND。MODE_ORIVATE表示覆盖内容,MODE_APPEND表示追加内容。两种模式都会在文件不存在的时候闯将文件。

public void Save(String inputText)
{
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try {
        out = openFileOutput("data", Context.MODE_PRIVATE);
        writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write(inputText);
    }catch (IOException e)
    {
        e.printStackTrace();
    }
    finally {
        try{
            if(writer != null)
                writer.close();
        }catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

protected void onDestroy() {
    super.onDestroy();
    Save(edit.getText().toString());
}


二、从文件中读取数据

Context类中提供了一个openFileInput()方法,用于从文件中读取数据,接受一个文件名参数。

public String load()
{
    FileInputStream in = null;
    BufferedReader reader = null;
    StringBuilder content = new StringBuilder();
    try{
        in = openFileInput("data");
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while((line = reader.readLine()) != null)
        {
            content.append(line);
        }
    }catch (IOException e)
    {
        e.printStackTrace();
    }
    finally {
        try{
            reader.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    return content.toString();
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView((R.layout.first_layout));

    edit = (EditText) findViewById(R.id.edit);
    String inputText = load();
    if(!TextUtils.isEmpty(inputText))
    {
        edit.setText(inputText);
        edit.setSelection(inputText.length());
        Toast.makeText(Main2Activity.this,"加载数据成功",Toast.LENGTH_SHORT).show();
    }
}

首页 我的博客
粤ICP备17103704号