android文件存储

来源:互联网 发布:淘宝牙齿美白仪有用吗 编辑:程序博客网 时间:2024/04/28 23:47

1、File存储

public class FileUtil {    public static final File sdCardDir = Environment.getExternalStorageDirectory(); //获取SDCard目录    public static final String NAME=FileHelper.PATH_BASE;    public  static void SaveToFile(String result,String filename){        try {            filename = filename.substring(HttpConfigUtil.URL_BASE.length(),filename.length());            Log.i("YUQING","SaveToFile filename="+filename);            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){                File saveFile = new File(sdCardDir+File.separator+NAME,filename);                if (!saveFile.getParentFile().exists()) {                    saveFile.getParentFile().mkdirs();                }                FileOutputStream outStream = new FileOutputStream(saveFile);                outStream.write(result.getBytes());                outStream.close();            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    public static String getFileData(String filename){        String result = null;        filename = filename.substring(HttpConfigUtil.URL_BASE.length(),filename.length());        File file = new File(sdCardDir+File.separator+NAME,filename);        if (file.exists() && file.isFile()) {            result =readFromFile(file);        }        return result;    }    private static String readFromFile(File file) {        StringBuffer sb = new StringBuffer();        try {            BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));            FileInputStream fis = new FileInputStream(file);            int c;            while ((c = br.read()) != -1) {                sb.append((char) c);            }            br.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return sb.toString();    }}

2、SQLite方法存储

先记录下一些简单的操作数据库的sql语句:
/*
* 几个简单的sql语句:
* 选择:Select * from mytable where itemId=1
* 插入:insert into mytable(itemId,name,content) values(33,”xxxx”,”xxxxx”)
* 删除:delete from mytable where itemId=1
* 更新:update mytable set name=”yyy” where itemId=33
* 查找:select * from mytable where name like ‘%yy%’
* 排序:select * from mytable order by itemId desc (asc升序)
* 总数:select count(*) from mytable
*/

a、创建DbOpenHelper.java

继承SQLiteOpenHelper,主要是创建和更新数据库操作。

DbOpenHelper.java

public class DbOpenHelper extends SQLiteOpenHelper{    private static final String DATABASENAME = "collection.db";    public static final String TABLENAME = "collectiontable";    private static int VERSION = 1;    private final String sql = "CREATE TABLE " + TABLENAME + "("            + "id           INTEGER         PRIMARY KEY ,"      // 在SQLite中设置为Integer、PRIMARY KEY则ID自动增长            + "name         VARCHAR(100)    NOT NULL ,"            + "production   VARCHAR(1000)   NOT NULL ,"            + "score        VARCHAR(20)     NOT NULL ,"            + "picUrl       VARCHAR(100)    NOT NULL ,"            + "url          VARCHAR(100)    NOT NULL ,"            + "type         VARCHAR(100)    NOT NULL "+ ")";    /*     * Create a helper object to create, open, and/or manage a database.      * This method always returns very quickly.      * The database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.     */    public DbOpenHelper(Context context) {        super(context, DATABASENAME, null, VERSION);        // TODO Auto-generated constructor stub    }    @Override    public void onCreate(SQLiteDatabase db) {        // TODO Auto-generated method stub        db.execSQL(sql);        LogCat.i("DbOpenHelper onCreate");    }    /*     * The SQLite ALTER TABLE documentation can be found here.      * If you add new columns you can use ALTER TABLE to insert them into a live table.      * If you rename or remove columns you can use ALTER TABLE to rename the old table, then create the new table and then populate the new table with the contents of the old table.      */    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        // TODO Auto-generated method stub        String sql_drop = "DROP TABLE IF EXISTS " + TABLENAME ;        db.execSQL(sql_drop) ;        db.execSQL(sql);    }}

b、数据库操作DataBaseOperate.java

获得DbOpenHelper对象,通过其对象获得SQLiteDatabase,进行增删改查

DataBaseOperate.java

public class DataBaseOperate {    private DbOpenHelper dbHelp = null;    public DataBaseOperate(DbOpenHelper dbHelp) {        // TODO Auto-generated constructor stub        this.dbHelp = dbHelp;    }    //当使用插入的时候,可以不执行sql语句,使用db.insert方法,用到ContentValue    public void add(Object[] params){        SQLiteDatabase db = null;        try {            String sql = "insert into "                    + DbOpenHelper.TABLENAME                    +"(name,production,score,picUrl,url,type) values(?,?,?,?,?,?)";            db = dbHelp.getWritableDatabase();            db.execSQL(sql, params);        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        }finally{            if(db != null){                db.close();            }        }    }    //按照itemId删除    public void delete(Object[] params){        SQLiteDatabase db = null;        try {            String sql = "delete from "+ DbOpenHelper.TABLENAME+" where name = ?";            db = dbHelp.getWritableDatabase();            db.execSQL(sql, params);        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        }finally{            if(db != null){                db.close();            }        }    }    //通过name找到值    public List<Map<String,String>> findMsg(String[] params){        SQLiteDatabase db = null;        List<Map<String,String>> list = new ArrayList<Map<String,String>>();        try {            String sql = "select * from "+ DbOpenHelper.TABLENAME+" where name = ?";            db = dbHelp.getWritableDatabase();            Cursor cursor = db.rawQuery(sql, params);            int colums = cursor.getColumnCount();//获得列数目            while(cursor.moveToNext()){                Map<String, String> map = new HashMap<String, String>();                for(int i=0;i<colums;i++){                    String columName = cursor.getColumnName(i);                    String columValue = cursor.getString(cursor.getColumnIndex(columName));                    if(columValue==null){                        columValue = "";                    }                    map.put(columName, columValue);                }                list.add(map);            }        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        }finally{            if(db != null){                db.close();            }        }        return list;    }    //更新itemId=1项的数据    public void update(Object[] params){        SQLiteDatabase db = null;        try {            String sql = "update "+ DbOpenHelper.TABLENAME+" set name = ?, production = ?, score = ? where itemId=1";            db = dbHelp.getWritableDatabase();            db.execSQL(sql, params);        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        }finally{            if(db != null){                db.close();            }        }    }    public List<Map<String,String>> findMsg(){        SQLiteDatabase db = dbHelp.getWritableDatabase();        List<Map<String,String>> all = new ArrayList<Map<String,String>>() ;        String sql = "SELECT name,production,score,picUrl,url,type FROM " + DbOpenHelper.TABLENAME;        Cursor result=null;        try {            result= db.rawQuery(sql, null); // 执行查询语句            for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {    // 采用循环的方式检索数据                Map<String,String> map = new HashMap<String,String>() ;                map.put("name", result.getString(0)) ;                map.put("production", result.getString(1)) ;                map.put("score",result.getString(2)) ;                map.put("pic_url",result.getString(3)) ;                map.put("url",result.getString(4));                map.put("type",result.getString(5));                all.add(map) ;            }        } catch (Exception e) {            e.printStackTrace();        }finally{            if(result!=null){                result.close();            }            if(db != null){                db.close();            }        }        return all ;    }}

c、代码中使用
DbOpenHelper mDbHelper = new DbOpenHelper(CollectionActivity.this);
DataBaseOperate mDatabase = new DataBaseOperate(mDbHelper);
然后通过mDatabase调用方法。

0 0