六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 237|回复: 0

DB和File工具类

[复制链接]

升级  14%

17

主题

17

主题

17

主题

秀才

Rank: 2

积分
71
 楼主| 发表于 2013-1-30 01:15:34 | 显示全部楼层 |阅读模式
DB工具类:
import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.List;import com.huawei.android.browser.fusion.FusionCode;import com.huawei.android.browser.service.file.FileHelper;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;public final class DBHelper extends SQLiteOpenHelper{/** * 数据库的版本号,默认情况下是1 */private static final int DATABASE_VERSION = 57;private static final String URL = "url";private static final String ID = "id";private static final String LOGO = "logo";//add by heping 2010-07-29 beginprivate static final String LOGOPATH = "logopath";//add by heping 2010-07-29 beginprivate static final String TITLE = "title";private static final String TIME = "time";private static final String SOURCE_FLAG = "sourceFlag";/** * 分类推荐表名和字段名常量定义 */public static final String SORT_OF_URL = "TB_SortOfUrl";public static final String SORT_OF_URL_ID = ID;public static final String SORT_OF_URL_TYPE = "type";public static final String SORT_OF_URL_TYPE_NAME = "typeName";public static final String SORT_OF_URL_URL = URL;public static final String SORT_OF_URL_TITLE = TITLE;public static final String SORT_OF_URL_LOGO = LOGO;/** * 书签表名和字段名常量定义 */public static final String BOOKMARK = "TB_Bookmark";public static final String BOOKMARK_ID = ID;public static final String BOOKMARK_NAME = "name";public static final String BOOKMARK_PARENTID = "parentId";public static final String BOOKMARK_ISDIR = "isDir";public static final String BOOKMARK_URL = URL;public static final String BOOKMARK_RANK = "rank";public static final String BOOKMARK_LOGO = LOGO;/** * 输入联想表名和字段名常量定义 */public static final String AUTO_COMPLETE = "TB_AutoComplete";public static final String AUTO_COMPLETE_ID = ID;public static final String AUTO_COMPLETE_URL = URL;public static final String AUTO_COMPLETE_TITLE = TITLE;public static final String AUTO_COMPLETE_SOURCE_FLAG = SOURCE_FLAG;/** * 未关闭网页表名和字段名常量定义 */public static final String UNCLOSED_PAGE = "TB_UnclosedPage";public static final String UNCLOSED_PAGE_ID = ID;public static final String UNCLOSED_PAGE_TITLE = TITLE;public static final String UNCLOSED_PAGE_URL = URL;public static final String UNCLOSED_PAGE_LOGO = LOGOPATH;/** * 设置管理表名和字段名常量定义 */public static final String SETTING = "TB_Setting";public static final String SETTING_ID = ID;public static final String SETTING_TYPE = "settingType";public static final String SETTING_NAME = "settingName";public static final String SETTING_VALUE_DESPLAY = "settingValueDesplay";public static final String SETTING_VALUE = "settingValue";public static final String SETTING_DEFAULT_VALUE = "settingDefaultValue";/** * 经常访问网页表名和字段名常量定义 */public static final String FREQUENTLY = "TB_Frequently";public static final String FREQUENTLY_ID = ID;public static final String FREQUENTLY_TITLE = TITLE;public static final String FREQUENTLY_URL = URL;public static final String FREQUENTLY_LOGO = LOGO;public static final String FREQUENTLY_COUNT = "count";/** * 我的应用表名和字段名常量定义 */public static final String APPLICATION = "TB_Application";public static final String APPLICATION_ID = ID;public static final String APPLICATION_PARENT_ID = "parentId";public static final String APPLICATION_IS_APP = "isApp";public static final String APPLICATION_LOGO = LOGO;public static final String APPLICATION_NAME = "name";public static final String APPLICATION_AUTHOR = "author";public static final String APPLICATION_VERSION = "version";public static final String APPLICATION_DESCRIPTION = "description";public static final String APPLICATION_CONTENT = "content";public static final String APPLICATION_NOTES = "notes";/** * 历史记录表名和字段名常量定义 */public static final String HISTORY = "TB_History";public static final String HISTORY_ID = ID;public static final String HISTORY_URL = URL;public static final String HISTORY_TITLE = TITLE;public static final String HISTORY_TIME = "additiveTime";public static final String HISTORY_LOGO = LOGO;public static final String HISTORY_SOURCE_FLAG = SOURCE_FLAG;/** * 文件下载表名和字段名常量定义 */public static final String DOWNLOAD_ITEM = "TB_DownloadItem";public static final String DOWNLOAD_ITEM_ID = ID;public static final String DOWNLOAD_ITEM_DOWN_URL = "downUrl";public static final String DOWNLOAD_ITEM_NAME = "name";public static final String DOWNLOAD_ITEM_STATUS = "status";public static final String DOWNLOAD_ITEM_SRC = "src";public static final String DOWNLOAD_ITEM_LENGTH = "length";/** * 流量统计表名和字段名常量定义 */public static final String COUNT_FLOW = "TB_CountFlow";public static final String COUNT_FLOW_ID = ID;public static final String COUNT_FLOW_FLOW = "flow";public static final String COUNT_FLOW_TOTAL_FLOW = "totalFlow";public static final String COUNT_FLOW_TIME = TIME;/** * 打印日志时日志信息中的标识符 */private static final String TAG = "DBHelper";/** * 数据库的名称 */private static final String DATABASE_NAME = "HWBrowser.db";private static DBHelper databaseHelper;private SQLiteDatabase database;private final Context context;private final String fileSeparator = "#";private final String tableLabel = "table";/** * 构造函数 *  * @param context *            UI环境上下文 */private DBHelper(final Context context){super(context, DATABASE_NAME, null, DATABASE_VERSION);this.context = context;}/** * 以单例模式创建DBHelper *  * @param context *            UI环境上下文 * @return DBHelper */public static DBHelper getInstance(final Context context){if (databaseHelper == null){databaseHelper = new DBHelper(context);}return databaseHelper;}@Overridepublic void onCreate(final SQLiteDatabase sqliteDatabase){final String createTable = "create table if not exists ";final String primaryKey = " Integer  primary key autoincrement,";final String text = " text,";final String longType = " long,";final String endWithText = " text)";final String blob = " blob)";final String integer = " integer,";final String createTableLog = "  create tables:";final String success = " success!";final char leftBracket = '(';final int stringBufferSize = 170;sqliteDatabase.beginTransaction();try{final StringBuffer sql = new StringBuffer(stringBufferSize);sql.append(createTable).append(SORT_OF_URL).append(leftBracket).append(SORT_OF_URL_ID).append(primaryKey).append(SORT_OF_URL_URL).append(text).append(SORT_OF_URL_TITLE).append(text).append(SORT_OF_URL_TYPE).append(text).append(SORT_OF_URL_TYPE_NAME).append(text).append(SORT_OF_URL_LOGO).append(blob);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + SORT_OF_URL + success);sql.delete(0, sql.length());sql.append(createTable).append(BOOKMARK).append(leftBracket).append(BOOKMARK_ID).append(primaryKey).append(BOOKMARK_ISDIR).append(integer).append(BOOKMARK_NAME).append(text).append(BOOKMARK_RANK).append(integer).append(BOOKMARK_PARENTID).append(integer).append(BOOKMARK_URL).append(text).append(BOOKMARK_LOGO).append(blob);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + BOOKMARK + success);sql.delete(0, sql.length());sql.append(createTable).append(AUTO_COMPLETE).append(leftBracket).append(AUTO_COMPLETE_ID).append(primaryKey).append(AUTO_COMPLETE_TITLE).append(text).append(AUTO_COMPLETE_URL).append(text).append(AUTO_COMPLETE_SOURCE_FLAG).append(endWithText);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + AUTO_COMPLETE + success);//modify by heping 2010-07-29 beginsql.delete(0, sql.length());sql.append(createTable).append(UNCLOSED_PAGE).append(leftBracket).append(UNCLOSED_PAGE_ID).append(primaryKey).append(UNCLOSED_PAGE_TITLE).append(text).append(UNCLOSED_PAGE_URL).append(text).append(UNCLOSED_PAGE_LOGO).append(endWithText);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + UNCLOSED_PAGE + success);//modify by heping 2010-07-29 endsql.delete(0, sql.length());sql.append(createTable).append(SETTING).append(leftBracket).append(SETTING_ID).append(primaryKey).append(SETTING_TYPE).append(text).append(SETTING_NAME).append(text).append(SETTING_VALUE_DESPLAY).append(text).append(SETTING_VALUE).append(text).append(SETTING_DEFAULT_VALUE).append(endWithText);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + APPLICATION + success);sql.delete(0, sql.length());sql.append(createTable).append(FREQUENTLY).append(leftBracket).append(FREQUENTLY_ID).append(primaryKey).append(FREQUENTLY_TITLE).append(text).append(FREQUENTLY_URL).append(text).append(FREQUENTLY_COUNT).append(text).append(FREQUENTLY_LOGO).append(blob);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + FREQUENTLY + success);sql.delete(0, sql.length());sql.append(createTable).append(APPLICATION).append(leftBracket).append(APPLICATION_ID).append(primaryKey).append(APPLICATION_AUTHOR).append(text).append(APPLICATION_CONTENT).append(text).append(APPLICATION_DESCRIPTION).append(text).append(APPLICATION_IS_APP).append(text).append(APPLICATION_NAME).append(text).append(APPLICATION_PARENT_ID).append(text).append(APPLICATION_VERSION).append(text).append(APPLICATION_NOTES).append(text).append(APPLICATION_LOGO).append(blob);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + APPLICATION + success);sql.delete(0, sql.length());sql.append(createTable).append(HISTORY).append(leftBracket).append(HISTORY_ID).append(primaryKey).append(HISTORY_TITLE).append(text).append(HISTORY_URL).append(text).append(HISTORY_TIME).append(longType).append(HISTORY_SOURCE_FLAG).append(text).append(HISTORY_LOGO).append(blob);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + HISTORY + success);sql.delete(0, sql.length());sql.append(createTable).append(DOWNLOAD_ITEM).append(leftBracket).append(DOWNLOAD_ITEM_ID).append(primaryKey).append(DOWNLOAD_ITEM_DOWN_URL).append(text).append(DOWNLOAD_ITEM_NAME).append(text).append(DOWNLOAD_ITEM_SRC).append(text).append(DOWNLOAD_ITEM_STATUS).append(text).append(DOWNLOAD_ITEM_LENGTH).append(endWithText);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + DOWNLOAD_ITEM + success);sql.delete(0, sql.length());sql.append(createTable).append(COUNT_FLOW).append(leftBracket).append(COUNT_FLOW_ID).append(primaryKey).append(COUNT_FLOW_FLOW).append(text).append(COUNT_FLOW_TOTAL_FLOW).append(text).append(COUNT_FLOW_TIME).append(endWithText);sqliteDatabase.execSQL(sql.toString());Log.i(TAG, createTableLog + COUNT_FLOW + success);try{init(sqliteDatabase);// 预置数据}catch (Exception e){Log.e(TAG, e + FusionCode.EMPTY_STRING);}sqliteDatabase.setTransactionSuccessful();}catch (Exception e){Log.e(TAG, "  create tables fail!" + e);}finally{sqliteDatabase.endTransaction();}}@Overridepublic void onUpgrade(final SQLiteDatabase sqliteDatabase,final int oldVersion, final int newVersion){final String dropTable = "drop table if exists ";sqliteDatabase.beginTransaction();try{sqliteDatabase.execSQL(dropTable + SORT_OF_URL);sqliteDatabase.execSQL(dropTable + AUTO_COMPLETE);//sqliteDatabase.execSQL(dropTable + BOOKMARK);//sqliteDatabase.execSQL(dropTable + UNCLOSED_PAGE);sqliteDatabase.execSQL(dropTable + SETTING);sqliteDatabase.execSQL(dropTable + HISTORY);sqliteDatabase.execSQL(dropTable + APPLICATION);Log.i(TAG, " database version control success");sqliteDatabase.setTransactionSuccessful();}catch (Exception e){Log.e(TAG, " database version control fail :" + e.getMessage());}finally{sqliteDatabase.endTransaction();}onCreate(sqliteDatabase);}/** * 关闭数据库 */public void closeDb(){if (database != null && database.isOpen()){database.close();}}/** * Convenience method for inserting a row into the database. *  * @param table *            the table to insert the row into * @param nullColumnHack *            SQL doesn't allow inserting a completely FusionCode.EMPTY_STRING row, so if *            initialValues is FusionCode.EMPTY_STRING this column will explicitly be assigned *            a NULL value * @param values *            this map contains the initial column values for the row. The *            keys should be the column names and the values the column *            values * @return the row ID of the newly inserted row, or -1 if an error occurred * @author shenghua.lin */public long insert(final String table, final String nullColumnHack,final ContentValues values){long rowid = -1;try{database = this.getWritableDatabase();rowid = database.insert(table, nullColumnHack, values);}catch (Exception e){e.printStackTrace();}finally{closeDb();}return rowid;}/** * Convenience method for deleting rows in the database. *  * @param table *            the table to delete from * @param whereClause *            the optional WHERE clause to apply when deleting. Passing null *            will delete all rows. * @param whereArgs * @return the number of rows affected if a whereClause is passed in, 0 *         otherwise. To remove all rows and get a count pass "1" as the *         whereClause. * @author shenghua.lin */public int delete(final String table, final String whereClause,final String[] whereArgs){int affectedCount = 0;try{database = this.getWritableDatabase();affectedCount = database.delete(table, whereClause, whereArgs);}catch (Exception e){Log.e(TAG, e + FusionCode.EMPTY_STRING);}finally{closeDb();}return affectedCount;}/** * Convenience method for updating rows in the database. *  * @param table *            the table to update in * @param values *            a map from column names to new column values. null is a valid *            value that will be translated to NULL. * @param whereClause *            the optional WHERE clause to apply when updating. Passing null *            will update all rows. * @param whereArgs * @return the number of rows affected * @author shenghua.lin */public int update(final String table, final ContentValues values,final String whereClause, final String[] whereArgs){int affectCount = 0;try{database = this.getWritableDatabase();affectCount = database.update(table, values, whereClause, whereArgs);}catch (Exception e){Log.e(TAG, e + FusionCode.EMPTY_STRING);}finally{closeDb();}return affectCount;}/** * Query the given table, returning a Cursor over the result set. *  * @param table *            The table name to compile the query against. * @param columns *            A list of which columns to return. Passing null will return *            all columns, which is discouraged to prevent reading data from *            storage that isn't going to be used. * @param selection *            A filter declaring which rows to return, formatted as an SQL *            WHERE clause (excluding the WHERE itself). Passing null will *            return all rows for the given table. * @param selectionArgs *            You may include ?s in selection, which will be replaced by the *            values from selectionArgs, in order that they appear in the *            selection. The values will be bound as Strings. * @param groupBy *            A filter declaring how to group rows, formatted as an SQL *            GROUP BY clause (excluding the GROUP BY itself). Passing null *            will cause the rows to not be grouped. * @param having *            A filter declare which row groups to include in the cursor, if *            row grouping is being used, formatted as an SQL HAVING clause *            (excluding the HAVING itself). Passing null will cause all row *            groups to be included, and is required when row grouping is *            not being used. * @param orderBy *            How to order the rows, formatted as an SQL ORDER BY clause *            (excluding the ORDER BY itself). Passing null will use the *            default sort order, which may be unordered. * @param limit *            Limits the number of rows returned by the query, formatted as *            LIMIT clause. Passing null denotes no LIMIT clause. * @return Cursor * @author shenghua.lin */public Cursor select(final String table, final String[] columns,final String selection, final String[] selectionArgs,final String groupBy, final String having, final String orderBy,final String limit){database = this.getReadableDatabase();final Cursor cursor = database.query(table, columns, selection,selectionArgs, groupBy, having, orderBy, limit);return cursor;}/** * 向数据库插入预置数据 *  * @param sqliteDatabase */private void init(final SQLiteDatabase sqliteDatabase){final List<String> dbList = FileHelper.loadDataBaseInit(context);final StringBuffer table = new StringBuffer();String[] args;InputStream imageInput;final ByteArrayOutputStream bytestream = new ByteArrayOutputStream();final ContentValues values = new ContentValues();final String imageDir = "dbimage/";int character;try{int size = dbList.size();String string;for (int i = 0; i < size; i++){string = dbList.get(i);args = string.split(fileSeparator);values.clear();for (String arg : args){// 没找到分隔符if (arg.indexOf(FusionCode.SPLIT_LETTER) == -1){continue;}// 表名if (arg.startsWith(tableLabel)){table.delete(0, table.length());table.append(arg.substring(arg.indexOf(FusionCode.SPLIT_LETTER) + 1).trim());}else// 列名~值{if (arg.startsWith(LOGO)){// 获取图片资源imageInput = context.getAssets().open(imageDir+ arg.substring(arg.indexOf(FusionCode.SPLIT_LETTER) + 1).trim());bytestream.reset();// 将图片流转换成byte[]character = imageInput.read();while (character != -1){bytestream.write(character);character = imageInput.read();}values.put(LOGO, bytestream.toByteArray());}else// 字符串{values.put(arg.substring(0,arg.indexOf(FusionCode.SPLIT_LETTER)).trim(), arg.substring(arg.indexOf(FusionCode.SPLIT_LETTER) + 1).trim());}}}sqliteDatabase.insert(table.toString(), null, values);}}catch (IOException e){Log.e(TAG, e + FusionCode.EMPTY_STRING);}finally{if (bytestream != null){try{bytestream.close();}catch (IOException e){Log.e(TAG, e + FusionCode.EMPTY_STRING);}}}}}

File工具类:
import java.io.*;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.huawei.android.browser.R;import com.huawei.android.browser.fusion.FusionField;import com.huawei.android.browser.util.SDNotEnouchSpaceException;import com.huawei.android.browser.util.SDUnavailableException;import android.content.Context;import android.os.Environment;import android.os.StatFs;import android.util.Log;public final class FileHelper{/** * 这是程序第一次安装的时候在sd卡的主目录下生成的默认下载路径,系统下载的文件都放在 /sdcard/AppMarket/DownLoad/目录下 *///public final static String DOWNLOADPATH = Environment//.getExternalStorageDirectory().getAbsolutePath()//+ "/AppMarket/DownLoad/";public final static String DOWNLOADPATH = "/sdcard/";public final static String INSTALLPATH = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/AppMarket/Install/";/** * 当出错的时候返回的字节数为-1 */public final static int ERROR = -1;/** * 当没有写入任何数据的时候返回0 */public final static int NONE = 0;/** * 该变量是从sd卡读取文件时默认的字符缓冲区的大小 */private final static int MAX_LENTH = 1024;/** * sd卡所在的区块位置 */private final static int SDCARD_SYSTEM = 4;private static final String TAG = "FileHelper";private static final String EMPTY = "";private FileHelper(){}/** * 在程序第一次安装的时候就在sd卡的主目录下新建一个系统所需的目录 *  * @return 创建目录是否成功 */public static boolean makeDir(){boolean isComplete = false;// 创建下载目录File file = new File(DOWNLOADPATH);if (!isFileExist(file)){isComplete = file.mkdirs();}// 创建安装目录file = new File(INSTALLPATH);if (!isFileExist(file)){isComplete = file.mkdirs();}return isComplete;}/** * 创建widget安装路径 *  * @param widgetName *            widget的路径名 * @return 创建目录是否成功 */public static boolean makeWidgetDir(final String widgetName){boolean isComplete = false;final File file = new File(INSTALLPATH + widgetName + "/");if (!isFileExist(file)){isComplete = file.mkdirs();}return isComplete;}/** * 通过提供的文件名在默认路径下生成文件 *  * @param fileName *            文件的名称 * @return 生成的文件 */public static File createFile(final String fileName){final File file = new File(DOWNLOADPATH + fileName);Log.i(TAG, file.getPath());if (!isFileExist(file)){try{file.createNewFile();}catch (IOException e){Log.e(TAG, e + EMPTY);}}return file;}/** * 将从下载管理那里获取来的数据流写入文件中 *  * @param ops *            从下载管理那里获取来的io流 * @param fileName *            需要存储的文件的路径和名称 * @return 总共存储成功的字节数 * @throws SDNotEnouchSpaceException * @throws SDUnavailableException */public static int writeFile(final byte[] io, final String fileName)throws SDUnavailableException, SDNotEnouchSpaceException{int length = NONE;if (io != null){RandomAccessFile file = null;try{file = new RandomAccessFile(createFile(fileName), "rw");file.seek(file.length());file.write(io);}catch (IOException e){Log.e(TAG, e + EMPTY);checkSD(io);// 如果出现异常,返回的字节数为-1,表示出现了异常,没有写入成功return ERROR;}finally{try{file.close();}catch (IOException e){Log.e(TAG, e + EMPTY);}}length = io.length;}return length;}/** * 将从网络获取来的数据流写入文件中 *  * @param ops *            从网络获取来的io流 * @param fileName *            需要存储的文件的名称 * @return 总共存储成功的字节数 * @throws SDNotEnouchSpaceException * @throws SDUnavailableException */public static int writeFile(final RandomAccessFile file, final byte[] io)throws SDUnavailableException, SDNotEnouchSpaceException{int length = NONE;if (io != null){if (file != null){try{file.seek(file.length());file.write(io);}catch (IOException e){Log.e(TAG, e + EMPTY);checkSD(io);// 如果出现异常,返回的字节数为-1,表示出现了异常,没有写入成功return ERROR;}// Log.i("aaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaa");length = io.length;}else{checkSD(io);// 如果出现异常,返回的字节数为-1,表示出现了异常,没有写入成功return ERROR;}}return length;}/** * 从本地文件中读取文件信息 *  * @param fileName *            文件的名称 * @return 文件中的信息 */public static String readFile(final String fileName){RandomAccessFile file = null;final byte[] buffer = new byte[MAX_LENTH];final StringBuffer content = new StringBuffer();try{file = new RandomAccessFile(createFile(fileName), "rw");while (file.read(buffer) != -1){content.append(new String(buffer));}}catch (IOException e){Log.e(TAG, e + EMPTY);}finally{try{file.close();}catch (IOException e){Log.e(TAG, e + EMPTY);}}return content.toString();}/** * 是否存在此文件 *  * @param file *            判断是否存在的文件 * @return 存在返回true,否则返回false */public static boolean isFileExist(final File file){return file.exists();}/** * 删除路径指向的文件 *  * @param fileName *            文件的名称 */public static boolean deleteFile(final String filePath){boolean isComplete = false;final File file = new File(filePath);//final File file = new File(DOWNLOADPATH + fileName);if (file.exists()){Log.i(TAG, "delete Success==========");isComplete = file.delete();}else{Log.i(TAG, "delete not exist==========");isComplete = true;}return isComplete;}/** * 取得下载进度 *  * @param fileName *            文件的名称 * @param fileSize *            文件的总大小 * @return 下载进度的百分比 */public static int getProgress(final String fileName, final long fileSize){if (fileSize != 0){return (int) ((getLocalFileSize(fileName) * 100) / fileSize);}return 0;}/** * 本地文件大小 *  * @param fileName *            文件的名称 * @return 返回文件的大小 */public static long getLocalFileSize(final String fileName){final File file = createFile(fileName);long length = 0;if (isFileExist(file)){length = file.length();}return length;}/** * 读取配置文件读取配置信息 *  * @param context *            调用这个方法的activity * @return 包含配置信息的hashmap键值对 */public static Map<String, String> loadProperties(final Context context){final HashMap<String, String> properties = new HashMap<String, String>();InputStream inputStream = null;// 将配置文件放到res/raw/目录下,可以通过以下的方法获取inputStream = context.getResources().openRawResource(R.raw.system);/* * 这是读取配置文件的第二种方法 将配置文件放到assets目录下,可以通过以下的方法获取 is = * context.getAssets().open("system.properties"); */// 用来提取键值对的临时字符串final StringBuffer tempStr = new StringBuffer();// 用来存放读取的每个字符int character = 0;// 分隔符在字符串中的位置,分隔符为":"int index = 0;// 用来保存读取的配置文件一行的信息String line = null;// //一次读取1024个字节,如果遇到换行就读取到这一行为止// byte[] content = new byte[MAX_LENTH];try{while (character != -1){tempStr.delete(0, tempStr.length());character = inputStream.read();while (character != -1){if (character == '\n'){break;}else{tempStr.append((char) character);}character = inputStream.read();}// ch = is.read(content);line = tempStr.toString().trim();// line = new String(content);// 判断读出的那行数据是否有效,#开头的代表注释,如果是注释行那么跳过下面,继续上面操作if (line.length() == 0 || line.charAt(0) == '#'){continue;}// 查找key与value的分隔符,:index = line.indexOf(':');// 如果没有跳过下面,继续上面操作if (index == -1){continue;}// 将key与value对应的值保存进hashtableproperties.put(line.substring(0, index), line.substring(index + 1));}}catch (IOException e){Log.e(TAG, e + EMPTY);}finally{try{inputStream.close();}catch (IOException e){Log.e(TAG, e + EMPTY);}}return properties;}/** * 读取数据库预置文件database_init.properties *  * @param context *            调用这个方法的activity * @return List<String> * @author shenghua.lin * @creatTime 2010.06.11 */public static List<String> loadDataBaseInit(final Context context){final List<String> properties = new ArrayList<String>(150);InputStream inputStream = null;Reader reader = null;BufferedReader bufferedReader = null;/* * 这是读取配置文件的第二种方法 将配置文件放到assets目录下,可以通过以下的方法获取 */try{inputStream = context.getAssets().open("database_init.properties");reader = new InputStreamReader(inputStream);bufferedReader = new BufferedReader(reader);// 用来保存读取的配置文件一行的信息String line = bufferedReader.readLine();while (line != null){if (!line.trim().equals(EMPTY)){properties.add(line);}line = bufferedReader.readLine();}}catch (IOException e){Log.e(TAG, e.getMessage());}finally{if (bufferedReader != null){try{bufferedReader.close();}catch (IOException e){Log.e(TAG, e + EMPTY);}}if (reader != null){try{reader.close();}catch (IOException e){Log.e(TAG, e + EMPTY);}}if (inputStream != null){try{inputStream.close();}catch (IOException e){Log.e(TAG, e + EMPTY);}}}return properties;}/** * 对sdcard的检查,主要是检查sd是否可用,并且sd卡的存储空间是否充足 *  * @param io *            写入sd卡的数据 * @throws SDUnavailableException * @throws SDNotEnouchSpaceException */public static void checkSD(final byte[] io) throws SDUnavailableException,SDNotEnouchSpaceException{if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){if (io.length >= getFreeSD()){throw new SDNotEnouchSpaceException(FusionField.currentActivity.getString(R.string.sd_NotEnoughSpace));}}else{throw new SDUnavailableException(FusionField.currentActivity.getString(R.string.sd_Unavailable));}}/** * 获取SD卡的剩余空间 *  * @return SD卡的剩余的字节数 */public static long getFreeSD(){long nAvailableCount = 0l;StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());nAvailableCount = (long) (stat.getBlockSize() * ((long) stat.getAvailableBlocks() - SDCARD_SYSTEM));return nAvailableCount;}}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表