`
zxl_ong
  • 浏览: 128764 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

DB和File工具类

阅读更多
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 begin
	private static final String LOGOPATH = "logopath";
	//add by heping 2010-07-29 begin
	private 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;
	}

	@Override
	public 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 begin
			sql.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 end

			sql.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();
		}
	}

	@Override
	public 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对应的值保存进hashtable
				properties.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;
	}
}
分享到:
评论

相关推荐

    查看android的数据库文件db工具

    在Android开发中,数据库是存储和管理应用程序数据的重要手段,SQLite是Android系统默认使用的轻量级关系型数据库。...在实际开发中,掌握这类工具的使用对于提升工作效率和解决数据相关问题至关重要。

    配置文件读取工具类(Java)

    为了方便地读取和管理这些配置文件,开发者会创建专门的工具类。以下是一个关于如何构建和使用配置文件读取工具类的详细说明。 1. **配置文件格式** 配置文件通常使用如INI、XML或JSON等易于解析的格式。在Java中...

    eclipse中有关mysql数据库工具类编写的例子

    ### Eclipse中MySQL数据库工具类编写详解 在Java开发过程中,我们经常会...在实际开发中,还可以进一步优化和完善这个工具类,例如引入连接池技术来提高性能和稳定性,以及增加更多实用的功能来满足复杂的应用需求。

    自己封装的一些文件(夹)操作和txt文件读写的工具类 哈哈(ExtUtil0.2)

    在这个名为"哈哈(ExtUtil0.2)"的项目中,作者提供了一些自定义的工具类,专门用于简化这些常见的文件和文件夹操作,同时包含了对TXT文件的读写功能。下面我们将详细探讨这些知识点。 首先,工具类(Tool Class)...

    安卓 db数据库查看工具

    本主题主要关注的是一个名为"安卓 db数据库查看工具"的实用程序,该工具允许用户直接打开和查看.db文件,无需通过Android设备或模拟器的复杂操作。描述中提到,这个工具只需安装后即可使用,简化了数据库管理的过程...

    Java解析XML工具类--(java源码)

    Document domTree = db.parse( xmlFile ); return domTree; } /** * 获得某节点下的某个子节点(指定子节点名称,和某个属性的值) * 即获取parentElement下名字叫childName,并且属性attributeName...

    .NET常用的工具类

    8. **线程和异步编程**:`System.Threading`命名空间提供了线程和同步原语,如`Thread`类和`Mutex`类。`async/await`关键字使得异步编程更加简洁。 9. **网络通信**:`System.Net`命名空间包含用于网络通信的类,如...

    DB2的JAR包

    它包含了与DB2交互所需的Java接口和类,是连接DB2所必需的。 2. **db2jcc.jar**:DB2 Java Connectivity Client,这是DB2的JDBC类型4驱动程序,实现了完整的JDBC 4.2规范。它是一个纯Java实现的驱动,无需依赖本地...

    QQ .db文件瘦身器

    这类文件是只增不减的,比如就算你删除了所有旧的信息, msg2.0.db仍然是原来大小。 因此做了这个工具,他的目的是主要是重新整理 msg2.0.db文件。让删除历史记录后的空间剩余出来,便于备份。 比方说我的 msg2.0....

    R包GO.db_3.0.0.zip

    `GO.db`包是R中的一个重要工具,它为GO数据提供了方便的数据库接口,使得研究人员能够进行GO注释、富集分析以及功能解读。 `GO.db`包包含三个主要的GO术语集合:生物学过程(Biological Process)、细胞成分...

    File2DB:文件导入数据库通用组件

    - `src`目录:源代码,包括主要的Java类和接口,如文件解析器、数据库连接管理、数据映射等。 - `config`目录:配置文件,可能包括数据库连接配置、文件读取配置等。 - `lib`目录:依赖的第三方库,如数据库驱动、...

    DB2 v9.7 java development

    通过利用JDBC和SQLJ接口,以及丰富的工具和配置选项,Java开发者能够在多种操作系统平台上构建高效、可靠的数据库应用程序。掌握DB2 v9.7的Java开发技巧,无疑将极大提升个人在数据库领域的专业能力,为职业生涯的...

    DB4o 数据库实例

    你可以通过对象实例或类来检索数据,也可以利用字段和条件进行过滤。 5. **版本控制与事务处理**: DB4o支持版本控制,每个对象都有一个版本号,这有助于解决并发更新问题。同时,它也提供了事务处理,确保数据...

    HTML5本地存储——IndexedDB

    与传统的Web存储如Cookie和localStorage相比,IndexedDB提供了更高级别的数据管理能力。Cookie通常用于存储少量信息,而localStorage虽然可以存储更多数据,但不支持索引和复杂的查询操作。 IndexedDB的架构由以下...

    DB4o 将一个对象保存到文件中,然后查询读取

    通过深入学习DB4o的API和特性,你可以更好地利用这个工具来简化对象持久化的工作流程。 总结一下,DB4o是一个强大且灵活的对象数据库,它可以简化Java开发中的数据存储和检索。通过配置对象、打开数据库、存储和...

    Quartus Setting file reference manual

    `ELF_FILE` 用于定义可执行和链接格式文件的位置。这些文件在嵌入式系统设计中非常重要。 ##### ENABLE_COMPACT_REPORT_TABLE `ENABLE_COMPACT_REPORT_TABLE` 选项控制是否启用紧凑报告表。启用后,报告文件将更加...

    ASP 分页类 Kin_Db_Pager

    总之,ASP 分页类 Kin_Db_Pager 是一个强大的工具,它简化了 ASP 应用程序中分页功能的实现,让开发者能更专注于业务逻辑的开发,同时确保了系统的性能和用户体验。通过理解和熟练运用此类库,可以提升 ASP 项目的...

    【实战Apache-Flume采集DB数据到kafka】

    - 可以通过 Flume 的日志输出和 Kafka 的消费者工具来监控数据的流动和完整性。 7. **第三方 jar**: - 在配置 JDBC Source 时,可能需要添加数据库特定的 JDBC 驱动 jar 文件到 Flume 的类路径中。这可以通过在 ...

    C#读取thumbs.db类库下载.rar

    2. 使用类库:导入类库的命名空间,以便在代码中使用其提供的类和方法。例如: ```csharp using ThumbDBLib; // 假设这是ThumbDBLib.dll的命名空间 using ThumbsDbViewer_CSharp; // 假设这是ThumbsDbViewer_CSharp....

    安卓SQLite数据库相关-android读取本地.db文件实现不变数据本地化.rar

    总之,Android应用中的SQLite数据库是数据存储的关键工具,通过创建SQLiteOpenHelper子类、操作SQL语句以及复制预置.db文件,我们可以实现数据的本地化存储,满足应用对数据持久化的需要。对于初学者来说,理解和...

Global site tag (gtag.js) - Google Analytics