向内置存储卡内写入和读出文件

来源:互联网 发布:苹果mac常用软件 编辑:程序博客网 时间:2024/06/04 23:34

先看代码

public class sdcard extends Activity{    private EditText editText;    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.sdcardlayout);        editText = (EditText) findViewById(R.id.editText2);     /*   Button button = (Button) findViewById(R.id.button5);        button.setOnClickListener(new View.OnClickListener()        {            @Override            public void onClick(View v)            {                Toast.makeText(sdcard.this,"sdsfd",Toast.LENGTH_SHORT);            }        });*/    }    public void read(View view)    {        try        {            File file = new File("/data/data/com.example.zhao.menu/files/config.txt");            FileInputStream in = new FileInputStream(file);            int length = in.available();            byte[] buffer = new byte[length];            in.read(buffer);            String str = new String(buffer);            Toast.makeText(sdcard.this,str,Toast.LENGTH_SHORT).show();        } catch (FileNotFoundException e)        {            e.printStackTrace();        } catch (IOException e)        {            e.printStackTrace();        }    }    public void  write(View view)    {        try        {            FileOutputStream out = sdcard.this.openFileOutput("config.txt", Context.MODE_APPEND);            String str = editText.getText().toString();            out.write(str.getBytes());            out.flush();            out.close();            Toast.makeText(sdcard.this,str,Toast.LENGTH_SHORT).show();        } catch (IOException e)        {            e.printStackTrace();        }       /* File file=new File(Environment.getExternalStorageDirectory(), "log.txt");        OutputStream out= null;        try        {            out = new FileOutputStream(file);            String str = "dsfsdfsdfds";            out.write(str.getBytes());            out.close();        } catch (FileNotFoundException e)        {            e.printStackTrace();        } catch (IOException e)        {            e.printStackTrace();        }*/    }

要注意写好的文件存储在
/data/data/包名/files/文件名

0 0
原创粉丝点击