文件保存和读取

来源:互联网 发布:东方网络股票 编辑:程序博客网 时间:2024/04/30 06:35
case R.id.btn_save:                    try {                        String saveinfo = editText.getText().toString();                        FileOutputStream fos = openFileOutput("data.txt", Context.MODE_PRIVATE);                        fos.write(saveinfo.getBytes());                        fos.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                    Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_SHORT).show();                    break;                case R.id.btn_read:                    String content = "";                    try {                        FileInputStream fis = openFileInput("data.txt");                        byte[] buffer = new byte[fis.available()];                        fis.read(buffer);                        content = new String(buffer);                        fis.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                    Toast.makeText(MainActivity.this, "保存的数据是:" + content, Toast.LENGTH_SHORT).show();                    break;

第二种:

//保存数据private void save() {        editStr = editText.getText().toString();        try {            FileOutputStream fos = openFileOutput("info.txt", MODE_PRIVATE);            PrintStream ps = new PrintStream(fos);            ps.print(editStr);            ps.close();            fos.close();        } catch (Exception e) {            e.printStackTrace();        }    }    //读取数据    private void read() {        try {            buffer = new StringBuffer("");            FileInputStream fis = openFileInput("info.txt");            byte[] by = new byte[1024];            int line = 0;            while ((line = fis.read(by)) != -1){                buffer.append(new String(by, 0, line));            }            fis.close();            //此时读取的数据是buffer,toString            editText.setText(buffer.toString());        } catch (Exception e) {            e.printStackTrace();        }    }

读取assets文件夹下的文件(新建assets文件夹在Project视图src/main目录下):

try{ AssetManager assets = getResources().getAssets(); InputStream is = assets.open("qq.png", MODE_PRIVATE); image = BitmapFactory.decodeStream(is);  is.close();  }catch(Exception e){  e.printStackTrace();  }iv_image.setImageBitmap(image);读取RAW文件(在src/main/rec/raw目录下):StringBuffer buffer=new StringBuffer("");try{ InputStream is=getResources().openRawResource(R.raw.info); byte[] by=new byte[1024]; int line; while((line=is.read(by))!=-1){ buffer.append(new String(by,0,line));}}catch (Exception e) {                    e.printStackTrace();                }
0 0
原创粉丝点击