安卓第一行代码之数据存储

时间:2022-08-26 05:32:49

文件存储的基本思路:

写入:

String data = "this is the data";

FileOutputStream out =null;

BufferedWriter writer = null;

try

{

    out = openFileOutput("content_path",MODE_PRIVATE/MODE_APPEND);

    writer = new BufferedWriter(new OutputStreamWriter(out));

    writer.write(data);

}

catch(IOException e)

{

    e.printStackTrace();

}

finally

{

    try

        {

            if(writer!=null)

            {

                writer.close();

            }

            catch(IOException e)

            {

                e.printStackTrace();

            }

        }

}

读取:

FileInputStream in =null;

BufferedReader reader =null;

StringBuilder builder = new StringBuilder();

try

{

    in = openFileInput("content_path");

    reader = new BufferedReader(new InputStreamReader(in));

    String line="";

    while(line=reader.readLine()!=null)

    {

        builder.append(line);

    }

}

catch(IOException e)

{

    e.printStackTrace();

}

finally

{

    try

        {

            if(reader!=null)

            {

                reader.close();

            }

        }

            catch(IOException e)

            {

                e.printStackTrace();

            }

}