您的位置:首页 > 移动开发 > Android开发

从android选取文件获取文件路径,并将文件读入到数据库中,有进度条显示

2014-04-01 10:13 337 查看
大概流程:

点击选择文件按钮,出来MyFileManager对话框,从而选择文件路径,获取文件路径,对文件进行读取,并插入到数据库中

选取文件获取文件名及路径方法 PS:被屏蔽掉的代码,如果恢复正常,则可以判断文件类型,从而进行打开

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MyFileManager extends ListActivity {
private List<String> items = null;
private List<String> paths = null;
private String rootPath = "/";
private String curPath = "/";
private TextView mPath;

private final static String TAG = "bb";

@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.fileselect);
mPath = (TextView) findViewById(R.id.mPath);
//		Button buttonConfirm = (Button) findViewById(R.id.buttonConfirm);
//		buttonConfirm.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				Intent data = new Intent(MyFileManager.this, MainActivity.class);
//				Bundle bundle = new Bundle();
//				bundle.putString("file", curPath);
//				data.putExtras(bundle);
//				setResult(2, data);
//				finish();
//
//			}
//		});
//		Button buttonCancle = (Button) findViewById(R.id.buttonCancle);
//		buttonCancle.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				finish();
//			}
//		});
getFileDir(rootPath);
}

private void getFileDir(String filePath) {
mPath.setText(filePath);
items = new ArrayList<String>();
paths = new ArrayList<String>();
File f = new File(filePath);
File[] files = f.listFiles();

if (!filePath.equals(rootPath)) {
items.add("b1");
paths.add(rootPath);
items.add("b2");
paths.add(f.getParent());
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
items.add(file.getName());
paths.add(file.getPath());
}

setListAdapter(new MyAdapter(this, items, paths));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(paths.get(position));
if (file.isDirectory()) {
curPath = paths.get(position);
getFileDir(paths.get(position));
}else{
//	String fName = file.getName();
curPath=paths.get(position);
Intent data = new Intent(MyFileManager.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("file", curPath);
data.putExtras(bundle);
setResult(2, data);
finish();

}
//		else {
//			openFile(file);
//		}
}

//	private void openFile(File f) {
//		Intent intent = new Intent();
//		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		intent.setAction(android.content.Intent.ACTION_VIEW);
//
//		String type = getMIMEType(f);
//		intent.setDataAndType(Uri.fromFile(f), type);
//		startActivity(intent);
//	}

//	private String getMIMEType(File f) {
//		String type = "";
//		String fName = f.getName();
//		String end = fName
//				.substring(fName.lastIndexOf(".") + 1, fName.length())
//				.toLowerCase();
//
//		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
//				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
//			type = "audio";
//		} else if (end.equals("3gp") || end.equals("mp4")) {
//			type = "video";
//		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
//				|| end.equals("jpeg") || end.equals("bmp")) {
//			type = "image";
//		} else {
//			type = "*";
//		}
//		type += "/*";
//		return type;
//	}
}


读取文件并向手机数据库中插入文件记录适配器

public class MyDBAdapter {

private static String fileName;
private static final String DATABASE_NAME="sense.db";
private static final String DATABASE_TABLE="sense";
private static final int DATABASE_VERSION=1;

private static final String DATABASE_CREATE="create table "+DATABASE_TABLE+"(_id integer primary key autoincrement, lac char(8),cid char(8),name varchar(40))";

private SQLiteDatabase db;

private final Context context;

private myDbHelper dbHelper;

public MyDBAdapter(Context context,String fileName){
this.context=context;
this.fileName=fileName;
dbHelper=new myDbHelper(context,DATABASE_NAME,null,DATABASE_VERSION);

}
public MyDBAdapter(Context context){
this.context=context;
dbHelper=new myDbHelper(context,DATABASE_NAME,null,DATABASE_VERSION);

}

//	public boolean existDatabase(){
//		boolean flag=false;
//		try{
//
//			flag=true;
//		}catch(FileNotFoundException e){
//			flag=false;
//		}
//		return flag;
//	}

public boolean getcount(){
boolean flag=false;
Cursor cursor = null;
try {

cursor= db.query(DATABASE_TABLE,null,null,null,null,null,null);
System.out.println("总数据"+cursor.getCount());
if(cursor.getCount()>0){
flag = true;
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return flag;
}

public int loadDate(){
int count=0;
try {

System.out.println("######"+fileName);
InputStreamReader is = new InputStreamReader(new FileInputStream(new File(fileName)),"GBK");
BufferedReader cin = new BufferedReader(is);

String temp = null;
while ((temp =cin.readLine()) != null ){
count++;
String s[] = temp.split(",");
System.out.println("数据:"+s[0]+","+s[1]+","+s[2]);
if(s.length>0&&!s.equals("")){
long id = insertEntry(s[0].trim(),s[1].trim(),s[2].trim());
}
}

System.out.println("已插入第"+count+"条记录");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return count;

}

public MyDBAdapter open() throws SQLException{
db=dbHelper.getWritableDatabase();
return this;
}

public void close(){
db.close();
}

public long insertEntry(String lac,String cid,String name){
ContentValues contentValues=new ContentValues();
contentValues.put("lac", lac);
contentValues.put("cid", cid);
contentValues.put("name", name);
return db.insert(DATABASE_TABLE, null, contentValues);

}

public boolean removeEntry(){
return db.delete(DATABASE_TABLE, null, null)>0;
}

public String getEntry(String lac,String cid){
String[] result_columns=new String[]{"lac","cid"};
String where ="lac="+lac+" and cid="+cid;
Cursor result= db.query(DATABASE_TABLE,null,where,null,null,null,null);
String returnresult="";
while(result.moveToNext()){
//			 String nlac=result.getString(result.getColumnIndex("lac"));
//			 String ncid=result.getString(result.getColumnIndex("cid"));
String nname=result.getString(result.getColumnIndex("name"));
returnresult=nname;
System.out.println("查询出来的值是:"+lac+"   cid="+cid);
}
System.out.println("查询返回结果"+result);
return returnresult;
}

private static class myDbHelper extends SQLiteOpenHelper{
public myDbHelper(Context context,String name,CursorFactory factory,int version){
super(context,name,factory,version);
}

@Override
public void onCreate(SQLiteDatabase _db) {
// TODO Auto-generated method stub
_db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("数据库版本更新", "从"+oldVersion+"版本进化到"+newVersion+"版本");
_db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(_db);
}
}

}


在Activity中通过选择路径获取文件路径并执行插入数据库的调用方法

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

public static final int FILE_RESULT_CODE = 1;
//文件路径
private static String filepath="";
//判断是否选择文件,是则执行读取文件
private static boolean choosefile=false;
private static boolean listenlacid=false;
//读取文件进度条
private Handler handlerprogress = new Handler();
private ProgressDialog progressDialog = null;
//数据库适配器
private static MyDBAdapter dba;
private int loadcount=0;
private Button choose;
/**
*
* 文件路径获取
*
* */
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(layoutResID);
choose=(Button)findViewById(id);
choose.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//跳转到MyFileManager类,从而获取路径
Intent intent = new Intent(MainActivity.this,MyFileManager.class);
startActivityForResult(intent,FILE_RESULT_CODE);

}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(FILE_RESULT_CODE == requestCode){
Bundle bundle = null;
if(data!=null&&(bundle=data.getExtras())!=null){
filepath=bundle.getString("file");
System.out.println("@@@@@@"+filepath);
try {
//创建进度条对话框
progressDialog = ProgressDialog.show(MainActivity.this, "请稍等...", "正在导入数据中...", true);
dba=new MyDBAdapter(this, filepath);
dba.open();
//线程启动进度条
new Thread(new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
dba.removeEntry();
//导入并获取导入的数目
loadcount=dba.loadDate();
//更新完列表数据,则关闭对话框
progressDialog.dismiss();

}}).start();
choosefile=true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}


大概流程:

点击选择文件按钮,出来MyFileManager对话框,从而选择文件路径,获取文件路径,对文件进行读取,并插入到数据库中

选取文件获取文件名及路径方法 PS:被屏蔽掉的代码,如果恢复正常,则可以判断文件类型,从而进行打开

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MyFileManager extends ListActivity {
private List<String> items = null;
private List<String> paths = null;
private String rootPath = "/";
private String curPath = "/";
private TextView mPath;

private final static String TAG = "bb";

@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.fileselect);
mPath = (TextView) findViewById(R.id.mPath);
//		Button buttonConfirm = (Button) findViewById(R.id.buttonConfirm);
//		buttonConfirm.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				Intent data = new Intent(MyFileManager.this, MainActivity.class);
//				Bundle bundle = new Bundle();
//				bundle.putString("file", curPath);
//				data.putExtras(bundle);
//				setResult(2, data);
//				finish();
//
//			}
//		});
//		Button buttonCancle = (Button) findViewById(R.id.buttonCancle);
//		buttonCancle.setOnClickListener(new OnClickListener() {
//
//			public void onClick(View v) {
//				finish();
//			}
//		});
getFileDir(rootPath);
}

private void getFileDir(String filePath) {
mPath.setText(filePath);
items = new ArrayList<String>();
paths = new ArrayList<String>();
File f = new File(filePath);
File[] files = f.listFiles();

if (!filePath.equals(rootPath)) {
items.add("b1");
paths.add(rootPath);
items.add("b2");
paths.add(f.getParent());
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
items.add(file.getName());
paths.add(file.getPath());
}

setListAdapter(new MyAdapter(this, items, paths));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(paths.get(position));
if (file.isDirectory()) {
curPath = paths.get(position);
getFileDir(paths.get(position));
}else{
//	String fName = file.getName();
curPath=paths.get(position);
Intent data = new Intent(MyFileManager.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("file", curPath);
data.putExtras(bundle);
setResult(2, data);
finish();

}
//		else {
//			openFile(file);
//		}
}

//	private void openFile(File f) {
//		Intent intent = new Intent();
//		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		intent.setAction(android.content.Intent.ACTION_VIEW);
//
//		String type = getMIMEType(f);
//		intent.setDataAndType(Uri.fromFile(f), type);
//		startActivity(intent);
//	}

//	private String getMIMEType(File f) {
//		String type = "";
//		String fName = f.getName();
//		String end = fName
//				.substring(fName.lastIndexOf(".") + 1, fName.length())
//				.toLowerCase();
//
//		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
//				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
//			type = "audio";
//		} else if (end.equals("3gp") || end.equals("mp4")) {
//			type = "video";
//		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
//				|| end.equals("jpeg") || end.equals("bmp")) {
//			type = "image";
//		} else {
//			type = "*";
//		}
//		type += "/*";
//		return type;
//	}
}


读取文件并向手机数据库中插入文件记录适配器

public class MyDBAdapter {

private static String fileName;
private static final String DATABASE_NAME="sense.db";
private static final String DATABASE_TABLE="sense";
private static final int DATABASE_VERSION=1;

private static final String DATABASE_CREATE="create table "+DATABASE_TABLE+"(_id integer primary key autoincrement, lac char(8),cid char(8),name varchar(40))";

private SQLiteDatabase db;

private final Context context;

private myDbHelper dbHelper;

public MyDBAdapter(Context context,String fileName){
this.context=context;
this.fileName=fileName;
dbHelper=new myDbHelper(context,DATABASE_NAME,null,DATABASE_VERSION);

}
public MyDBAdapter(Context context){
this.context=context;
dbHelper=new myDbHelper(context,DATABASE_NAME,null,DATABASE_VERSION);

}

//	public boolean existDatabase(){
//		boolean flag=false;
//		try{
//
//			flag=true;
//		}catch(FileNotFoundException e){
//			flag=false;
//		}
//		return flag;
//	}

public boolean getcount(){
boolean flag=false;
Cursor cursor = null;
try {

cursor= db.query(DATABASE_TABLE,null,null,null,null,null,null);
System.out.println("总数据"+cursor.getCount());
if(cursor.getCount()>0){
flag = true;
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return flag;
}

public int loadDate(){
int count=0;
try {

System.out.println("######"+fileName);
InputStreamReader is = new InputStreamReader(new FileInputStream(new File(fileName)),"GBK");
BufferedReader cin = new BufferedReader(is);

String temp = null;
while ((temp =cin.readLine()) != null ){
count++;
String s[] = temp.split(",");
System.out.println("数据:"+s[0]+","+s[1]+","+s[2]);
if(s.length>0&&!s.equals("")){
long id = insertEntry(s[0].trim(),s[1].trim(),s[2].trim());
}
}

System.out.println("已插入第"+count+"条记录");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return count;

}

public MyDBAdapter open() throws SQLException{
db=dbHelper.getWritableDatabase();
return this;
}

public void close(){
db.close();
}

public long insertEntry(String lac,String cid,String name){
ContentValues contentValues=new ContentValues();
contentValues.put("lac", lac);
contentValues.put("cid", cid);
contentValues.put("name", name);
return db.insert(DATABASE_TABLE, null, contentValues);

}

public boolean removeEntry(){
return db.delete(DATABASE_TABLE, null, null)>0;
}

public String getEntry(String lac,String cid){
String[] result_columns=new String[]{"lac","cid"};
String where ="lac="+lac+" and cid="+cid;
Cursor result= db.query(DATABASE_TABLE,null,where,null,null,null,null);
String returnresult="";
while(result.moveToNext()){
//			 String nlac=result.getString(result.getColumnIndex("lac"));
//			 String ncid=result.getString(result.getColumnIndex("cid"));
String nname=result.getString(result.getColumnIndex("name"));
returnresult=nname;
System.out.println("查询出来的值是:"+lac+"   cid="+cid);
}
System.out.println("查询返回结果"+result);
return returnresult;
}

private static class myDbHelper extends SQLiteOpenHelper{
public myDbHelper(Context context,String name,CursorFactory factory,int version){
super(context,name,factory,version);
}

@Override
public void onCreate(SQLiteDatabase _db) {
// TODO Auto-generated method stub
_db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("数据库版本更新", "从"+oldVersion+"版本进化到"+newVersion+"版本");
_db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(_db);
}
}

}


在Activity中通过选择路径获取文件路径并执行插入数据库的调用方法

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

public static final int FILE_RESULT_CODE = 1;
//文件路径
private static String filepath="";
//判断是否选择文件,是则执行读取文件
private static boolean choosefile=false;
private static boolean listenlacid=false;
//读取文件进度条
private Handler handlerprogress = new Handler();
private ProgressDialog progressDialog = null;
//数据库适配器
private static MyDBAdapter dba;
private int loadcount=0;
private Button choose;
/**
*
* 文件路径获取
*
* */
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(layoutResID);
choose=(Button)findViewById(id);
choose.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//跳转到MyFileManager类,从而获取路径
Intent intent = new Intent(MainActivity.this,MyFileManager.class);
startActivityForResult(intent,FILE_RESULT_CODE);

}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(FILE_RESULT_CODE == requestCode){
Bundle bundle = null;
if(data!=null&&(bundle=data.getExtras())!=null){
filepath=bundle.getString("file");
System.out.println("@@@@@@"+filepath);
try {
//创建进度条对话框
progressDialog = ProgressDialog.show(MainActivity.this, "请稍等...", "正在导入数据中...", true);
dba=new MyDBAdapter(this, filepath);
dba.open();
//线程启动进度条
new Thread(new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
dba.removeEntry();
//导入并获取导入的数目
loadcount=dba.loadDate();
//更新完列表数据,则关闭对话框
progressDialog.dismiss();

}}).start();
choosefile=true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}


选取文件目录适配器

import java.io.File;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter
{
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Bitmap mIcon2;
private Bitmap mIcon3;
private Bitmap mIcon4;
private List<String> items;
private List<String> paths;
public MyAdapter(Context context,List<String> it,List<String> pa)
{
mInflater = LayoutInflater.from(context);
items = it;
paths = pa;
mIcon1 = BitmapFactory.decodeResource(context.getResources(),R.drawable.back01);
mIcon2 = BitmapFactory.decodeResource(context.getResources(),R.drawable.back02);
mIcon3 = BitmapFactory.decodeResource(context.getResources(),R.drawable.folder);
mIcon4 = BitmapFactory.decodeResource(context.getResources(),R.drawable.doc);
}

public int getCount()
{
return items.size();
}

public Object getItem(int position)
{
return items.get(position);
}

public long getItemId(int position)
{
return position;
}

public View getView(int position,View convertView,ViewGroup parent)
{
ViewHolder holder;

if(convertView == null)
{
convertView = mInflater.inflate(R.layout.file_row, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);

convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}

File f=new File(paths.get(position).toString());
if(items.get(position).toString().equals("b1"))
{
holder.text.setText("返回根目录..");
holder.icon.setImageBitmap(mIcon1);
}
else if(items.get(position).toString().equals("b2"))
{
holder.text.setText("返回上一层..");
holder.icon.setImageBitmap(mIcon2);
}
else
{
holder.text.setText(f.getName());
if(f.isDirectory())
{
holder.icon.setImageBitmap(mIcon3);
}
else
{
holder.icon.setImageBitmap(mIcon4);
}
}
return convertView;
}
private class ViewHolder
{
TextView text;
ImageView icon;
}
}


选取目录布局 file_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/listview_selected"
android:padding="6px"
>
<ImageView android:id="@+id/icon"
android:layout_width="30dip"
android:layout_height="30dip"
>
</ImageView>
<TextView android:id="@+id/text"
android:layout_gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@drawable/black"
>
</TextView>
</LinearLayout>
</LinearLayout>


fileselect.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="250px"
android:layout_height="330px"
android:orientation="vertical"
android:background="@drawable/white"
>
<TextView
android:id="@+id/mPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5px"
android:textSize="18sp"
android:textColor="@drawable/blue"
>
</TextView>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="330px"
>
</ListView>
<!--
<LinearLayout
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@android:id/list"
android:orientation="horizontal"
android:background="@drawable/white"
>
<Button
android:id="@+id/buttonConfirm"
android:layout_width="125px"
android:layout_height="fill_parent"
android:text="确定"
/>
<Button
android:id="@+id/buttonCancle"
android:layout_width="125px"
android:layout_height="fill_parent"
android:text="取消"
/>

</LinearLayout> -->
</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐