android简易文件管理器

eclipse下新建一个android工程:FileExplore,并在包下面建立FileExploreActivity;

其中代码如下:

  1 package zcw.softs;
2
3 import java.io.DataOutputStream;
4 import java.io.File;
5 import java.text.DecimalFormat;
6 import java.text.SimpleDateFormat;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 import android.app.AlertDialog;
11 import android.app.ListActivity;
12 import android.content.Context;
13 import android.content.DialogInterface;
14 import android.content.Intent;
15 import android.graphics.Color;
16 import android.net.Uri;
17 import android.os.Bundle;
18 import android.util.Log;
19 import android.view.KeyEvent;
20 import android.view.LayoutInflater;
21 import android.view.View;
22 import android.view.ViewGroup;
23 import android.widget.ArrayAdapter;
24 import android.widget.LinearLayout;
25 import android.widget.ListView;
26 import android.widget.TextView;
27
28 public class FileExploreActivity extends ListActivity {
29 private TextView currentFolder,countItems; //当前文件夹
30 private FileListAdapter fileList;
31
32 //文件过滤器,查找文件夹或文本文件
33 // private static final FileFilter BOOKS_FILTER = new FileFilter() {
34 // public boolean accept(File f) {
35 // return f.isDirectory() || f.getName().toLowerCase().matches("^.*?\\.(txt|text)$");
36 // return true;
37 // }
38 // };
39
40 public void onCreate(Bundle savedInstanceState) {
41 super.onCreate(savedInstanceState);
42 setContentView(R.layout.fileexplore1);
43 currentFolder = (TextView)findViewById(R.id.addbook_current_folder);
44 countItems = (TextView)findViewById(R.id.itemcount);
45
46 String apkRoot = "chmod 777 " + getPackageCodePath();
47 FileExploreActivity.RootCommand(apkRoot);
48
49 fill(new File("/"));
50 }
51
52 public boolean onKeyDown(int keyCode, KeyEvent event) {
53 if (keyCode == KeyEvent.KEYCODE_BACK && !fileList.isRoot) {
54 fill(fileList.getItem(0));
55 return true;
56 }
57 return super.onKeyDown(keyCode, event);
58 }
59 @Override
60 protected void onListItemClick(ListView l, View v, int position, long id) {
61 File file = fileList.getItem(position);
62 if(!file.canRead())
63 {
64 /* 弹出AlertDialog显示权限不足 */
65 new AlertDialog.Builder(this)
66 .setTitle("Message")
67 .setMessage("权限不足!")
68 .setPositiveButton("OK",
69 new DialogInterface.OnClickListener()
70 {
71 public void onClick(DialogInterface dialog,int which)
72 {
73 }
74 }).show();
75 }
76 else if (file.isDirectory())
77 fill(file);
78 else
79 {
80 openFile(file);
81 }
82 }
83 //跳转目录
84 private void fill(File folder) {
85 boolean isRoot = folder.getParent() == null;
86 currentFolder.setText(folder.getAbsolutePath());
87
88 List<File> files = new ArrayList<File>();
89 if (!isRoot)
90 files.add(folder.getParentFile());
91 File[] filterFiles = folder.listFiles();
92 countItems.setText(filterFiles.length+"项");
93 if(null != filterFiles && filterFiles.length>0) {
94 for (File file : filterFiles) {
95 files.add(file);
96 }
97 }
98 fileList = new FileListAdapter(this,android.R.layout.simple_list_item_1, files, isRoot);
99 setListAdapter(fileList);
100 }
101 public static boolean RootCommand(String command) {
102 Process process = null;
103 DataOutputStream os = null;
104 try {
105 process = Runtime.getRuntime().exec("su");
106 os = new DataOutputStream(process.getOutputStream());
107 os.writeBytes(command + "\n");
108 os.writeBytes("exit\n");
109 os.flush();
110 process.waitFor();
111 } catch (Exception e) {
112 Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
113 return false;
114 } finally {
115 try {
116 if (os != null) {
117 os.close();
118 }
119 process.destroy();
120 } catch (Exception e) {
121 }
122 }
123 Log.d("*** DEBUG ***", "Root SUC ");
124 return true;
125 }
126 /**
127 * 打开文件
128 * @param file
129 */
130 private void openFile(File file){
131
132 Intent intent = new Intent();
133 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
134 //设置intent的Action属性
135 intent.setAction(Intent.ACTION_VIEW);
136 //获取文件file的MIME类型
137 String type = getMIMEType(file);
138 //设置intent的data和Type属性。
139 intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
140 //跳转
141 try{
142 startActivity(intent);
143 }catch(Exception e){
144 System.out.print("未知类型,不能打开\n");
145 }
146 }
147
148 /**
149 * 根据文件后缀名获得对应的MIME类型。
150 * @param file
151 */
152 private String getMIMEType(File file) {
153
154 String type="*/*";
155 String fName = file.getName();
156 //获取后缀名前的分隔符"."在fName中的位置。
157 int dotIndex = fName.lastIndexOf(".");
158 if(dotIndex < 0){
159 return type;
160 }
161 /* 获取文件的后缀名 */
162 String end=fName.substring(dotIndex,fName.length()).toLowerCase();
163 if(end=="")return type;
164 //在MIME和文件类型的匹配表中找到对应的MIME类型。
165 for(int i=0;i<MIME_MapTable.length;i++){ //MIME_MapTable??在这里你一定有疑问,这个MIME_MapTable是什么?
166 if(end.equals(MIME_MapTable[i][0]))
167 type = MIME_MapTable[i][1];
168 }
169 return type;
170 }
171 private final String[][] MIME_MapTable={
172 //{后缀名, MIME类型}
173 {".3gp", "video/3gpp"},
174 {".apk", "application/vnd.android.package-archive"},
175 {".asf", "video/x-ms-asf"},
176 {".avi", "video/x-msvideo"},
177 {".bin", "application/octet-stream"},
178 {".bmp", "image/bmp"},
179 {".c", "text/plain"},
180 {".class", "application/octet-stream"},
181 {".conf", "text/plain"},
182 {".cpp", "text/plain"},
183 {".doc", "application/msword"},
184 {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
185 {".xls", "application/vnd.ms-excel"},
186 {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
187 {".exe", "application/octet-stream"},
188 {".gif", "image/gif"},
189 {".gtar", "application/x-gtar"},
190 {".gz", "application/x-gzip"},
191 {".h", "text/plain"},
192 {".htm", "text/html"},
193 {".html", "text/html"},
194 {".jar", "application/java-archive"},
195 {".java", "text/plain"},
196 {".jpeg", "image/jpeg"},
197 {".jpg", "image/jpeg"},
198 {".js", "application/x-javascript"},
199 {".log", "text/plain"},
200 {".m3u", "audio/x-mpegurl"},
201 {".m4a", "audio/mp4a-latm"},
202 {".m4b", "audio/mp4a-latm"},
203 {".m4p", "audio/mp4a-latm"},
204 {".m4u", "video/vnd.mpegurl"},
205 {".m4v", "video/x-m4v"},
206 {".mov", "video/quicktime"},
207 {".mp2", "audio/x-mpeg"},
208 {".mp3", "audio/x-mpeg"},
209 {".mp4", "video/mp4"},
210 {".mpc", "application/vnd.mpohun.certificate"},
211 {".mpe", "video/mpeg"},
212 {".mpeg", "video/mpeg"},
213 {".mpg", "video/mpeg"},
214 {".mpg4", "video/mp4"},
215 {".mpga", "audio/mpeg"},
216 {".msg", "application/vnd.ms-outlook"},
217 {".ogg", "audio/ogg"},
218 {".pdf", "application/pdf"},
219 {".png", "image/png"},
220 {".pps", "application/vnd.ms-powerpoint"},
221 {".ppt", "application/vnd.ms-powerpoint"},
222 {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
223 {".prop", "text/plain"},
224 {".rc", "text/plain"},
225 {".rmvb", "audio/x-pn-realaudio"},
226 {".rtf", "application/rtf"},
227 {".sh", "text/plain"},
228 {".tar", "application/x-tar"},
229 {".tgz", "application/x-compressed"},
230 {".txt", "text/plain"},
231 {".wav", "audio/x-wav"},
232 {".wma", "audio/x-ms-wma"},
233 {".wmv", "audio/x-ms-wmv"},
234 {".wps", "application/vnd.ms-works"},
235 {".xml", "text/plain"},
236 {".z", "application/x-compress"},
237 {".zip", "application/x-zip-compressed"},
238 {"", "*/*"}
239 };
240 }
241
242 //文件列表适配器
243 class FileListAdapter extends ArrayAdapter<File>{
244 private LayoutInflater mInflater;
245 boolean isRoot; //根目录
246
247 public FileListAdapter(Context context, int Resource, List<File> objects, boolean isRoot) {
248 super(context,Resource,objects);
249 this.isRoot = isRoot;
250 this.mInflater = LayoutInflater.from(context);
251 }
252
253 @Override
254 public View getView(int position, View convertView, ViewGroup parent) {
255 convertView = mInflater.inflate(R.layout.fileexplore2, null);
256 TextView title = (TextView)convertView.findViewById(R.id.addbook_title);
257 TextView file_size = (TextView)convertView.findViewById(R.id.file_size);
258 TextView file_type = (TextView)convertView.findViewById(R.id.file_type);
259 TextView file_date = (TextView)convertView.findViewById(R.id.file_edit_date);
260
261 File file = getItem(position);
262 if (position == 0 && !isRoot)
263 {
264 title.setText("返回上层");
265 title.setTextColor(Color.parseColor("#ffffff"));
266 title.setTextSize(36);
267 LinearLayout info= (LinearLayout)convertView.findViewById(R.id.file_info);
268 info.setVisibility(View.GONE);
269 }
270 else {
271 String filename=file.getName();
272 title.setText(filename);
273 if (file.isDirectory())
274 {
275 file_size.setText("文件夹");
276 file_size.setTextColor(Color.parseColor("#FF0011"));
277 }
278 else {
279 long fileSize = file.length();
280 if(fileSize >= 1024*1024) {
281 float size = fileSize/(1024f*1024f);
282 file_size.setText(new DecimalFormat("#.00").format(size) + "MB");
283 }else if(fileSize >= 1024) {
284 float size = fileSize/1024f;
285 file_size.setText(new DecimalFormat("#.00").format(size) + "KB");
286 }else {
287 file_size.setText(fileSize + "B");
288 }
289 int dot = filename.lastIndexOf('.');
290 if ((dot >-1) && (dot < (filename.length() - 1))) {
291 file_type.setText(filename.substring(dot + 1)+"文件");
292 }
293 file_date.setText(""+new SimpleDateFormat("yyyy/MM/dd HH:mm").format(file.lastModified()));
294 }
295 }
296 return convertView;
297 }
298 }

在layout文件夹下建立fileexplore1.xml作为listactivity的布局文件:

 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical"
4 android:layout_width="fill_parent"
5 android:layout_height="fill_parent">
6 <RelativeLayout
7 android:id="@+id/relativeLayout1"
8 android:layout_width="fill_parent"
9 android:layout_height="wrap_content" >
10
11 <TextView
12 android:id="@+id/addbook_current_folder"
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:layout_alignParentLeft="true"
16 android:layout_centerVertical="true"
17 android:textColor="#FFFFCC"
18 android:textSize="20sp" />
19
20 <TextView
21 android:id="@+id/itemcount"
22 android:layout_width="wrap_content"
23 android:layout_height="wrap_content"
24 android:textSize="20sp"
25 android:textColor="#C22"
26 android:layout_alignParentRight="true"
27 android:layout_centerVertical="true"/>
28
29 </RelativeLayout>
30 <LinearLayout
31 android:id="@+id/linearLayout2"
32 android:layout_width="fill_parent"
33 android:layout_height="2dip"
34 android:background="#09c"
35 android:orientation="vertical" >
36 </LinearLayout>
37
38 <LinearLayout
39 android:id="@+id/linearLayout1"
40 android:layout_width="fill_parent"
41 android:layout_height="wrap_content"
42 android:paddingLeft="8dip"
43 android:paddingRight="8dip"
44 android:orientation="vertical" >
45 <ListView
46 android:id="@android:id/list"
47 android:layout_width="fill_parent"
48 android:layout_height="wrap_content"
49 android:layout_weight="1"
50 android:cacheColorHint="#00000000"
51 android:fadeScrollbars="true"
52 android:drawSelectorOnTop="false"/>
53 </LinearLayout>
54 </LinearLayout>

注意其中ListView的id一定要设置为android:id="@android:id/list" 否则listactivity不能识别listview而报错;

在layout文件夹下建立fileexplore2.xmllistview的item的布局文件:

 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="wrap_content"
5 android:orientation="vertical" >
6
7 <TextView
8 android:id="@+id/addbook_title"
9 android:layout_width="wrap_content"
10 android:layout_height="wrap_content"
11 android:textColor="#FFF000"
12 android:textSize="20sp" />
13
14 <LinearLayout
15 android:id="@+id/file_info"
16 android:layout_width="fill_parent"
17 android:layout_height="wrap_content" >
18 <TextView
19 android:id="@+id/file_size"
20 android:layout_width="wrap_content"
21 android:layout_height="wrap_content"
22 android:textColor="#FFFFCC"
23 android:layout_weight="1"
24 android:textSize="10sp" />
25 <TextView
26 android:id="@+id/file_type"
27 android:layout_width="wrap_content"
28 android:layout_height="wrap_content"
29 android:textColor="#FFFFCC"
30 android:layout_weight="1"
31 android:gravity="right"
32 android:textSize="10sp" />
33 <TextView
34 android:id="@+id/file_edit_date"
35 android:layout_width="wrap_content"
36 android:layout_height="wrap_content"
37 android:layout_weight="1"
38 android:gravity="right"
39 android:textColor="#FFFFCC"
40 android:textSize="10sp" />
41 </LinearLayout>
42
43 </LinearLayout>



最后不要忘了在manifest中添加文件权限:

 

<uses-permission android:name="android.permission.RESTART_PACKAGES" ></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>


效果如下:

 

    






 

posted @ 2012-03-13 17:17  狂热与执着  阅读(1423)  评论(0编辑  收藏  举报