<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >java
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />android
</LinearLayout>app
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@android :id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>ide
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >post
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />ui
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" >
</TextView>
</LinearLayout>this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >.net
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />code
</RelativeLayout>xml
package com.wenjian;
import java.io.File;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private static final String ROOT_PATH = "/";
//存儲文件名稱
private ArrayList<String> names = null;
//存儲文件路徑
private ArrayList<String> paths = null;
private View view;
private EditText editText;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//顯示文件列表
showFileDir(ROOT_PATH);
}
private void showFileDir(String path){
names = new ArrayList<String>();
paths = new ArrayList<String>();
File file = new File(path);
File[] files = file.listFiles();
//若是當前目錄不是根目錄
if (!ROOT_PATH.equals(path)){
names.add("@1");
paths.add(ROOT_PATH);
names.add("@2");
paths.add(file.getParent());
}
//添加全部文件
for (File f : files){
names.add(f.getName());
paths.add(f.getPath());
}
this.setListAdapter(new MyAdapter(this,names, paths));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String path = paths.get(position);
File file = new File(path);
// 文件存在並可讀
if (file.exists() && file.canRead()){
if (file.isDirectory()){
//顯示子目錄及文件
showFileDir(path);
}
else{
//處理文件
fileHandle(file);
}
}
//沒有權限
else{
Resources res = getResources();
new AlertDialog.Builder(this).setTitle("Message")
.setMessage(res.getString(R.string.no_permission))
.setPositiveButton("OK",new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
super.onListItemClick(l, v, position, id);
}
//對文件進行增刪改
private void fileHandle(final File file){
OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 打開文件
if (which == 0){
openFile(file);
}
//修改文件名
else if(which == 1){
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
view = factory.inflate(R.layout.rename_dialog, null);
editText = (EditText)view.findViewById(R.id.editText);
editText.setText(file.getName());
OnClickListener listener2 = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String modifyName = editText.getText().toString();
final String fpath = file.getParentFile().getPath();
final File newFile = new File(fpath + "/" + modifyName);
if (newFile.exists()){
//排除沒有修改狀況
if (!modifyName.equals(file.getName())){
new AlertDialog.Builder(MainActivity.this)
.setTitle("注意!")
.setMessage("文件名已存在,是否覆蓋?")
.setPositiveButton("肯定", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int
which) {
if (file.renameTo(newFile)){
showFileDir(fpath);
displayToast("重命名成功!");
}
else{
displayToast("重命名失敗!");
}
}
})
.setNegativeButton("取消", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int
which) {
}
})
.show();
}
}
else{
if (file.renameTo(newFile)){
showFileDir(fpath);
displayToast("重命名成功!");
}
else{
displayToast("重命名失敗!");
}
}
}
};
AlertDialog renameDialog = new AlertDialog.Builder
(MainActivity.this).create();
renameDialog.setView(view);
renameDialog.setButton("肯定", listener2);
renameDialog.setButton2("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
renameDialog.show();
}
//刪除文件
else{
new AlertDialog.Builder(MainActivity.this)
.setTitle("注意!")
.setMessage("肯定要刪除此文件嗎?")
.setPositiveButton("肯定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(file.delete()){
//更新文件列表
showFileDir(file.getParent());
displayToast("刪除成功!");
}
else{
displayToast("刪除失敗!");
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
};
//選擇文件時,彈出增刪該操做選項對話框
String[] menu = {"打開文件","重命名","刪除文件"};
new AlertDialog.Builder(MainActivity.this)
.setTitle("請選擇要進行的操做!")
.setItems(menu, listener)
.setPositiveButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
//打開文件
private void openFile(File file){
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = getMIMEType(file);
intent.setDataAndType(Uri.fromFile(file), type);
startActivity(intent);
}
//獲取文件mimetype
private String getMIMEType(File file){
String type = "";
String name = file.getName();
//文件擴展名
String end = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
if (end.equals("m4a") || end.equals("mp3") || end.equals("wav")){
type = "audio";
}
else if(end.equals("mp4") || end.equals("3gp")) {
type = "video";
}
else if (end.equals("jpg") || end.equals("png") || end.equals("jpeg") || end.equals
("bmp") || end.equals("gif")){
type = "image";
}
else {
//若是沒法直接打開,跳出列表由用戶選擇
type = "*";
}
type += "/*";
return type;
}
private void displayToast(String message){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
public class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
private Bitmap directory,file;
//存儲文件名稱
private ArrayList<String> names = null;
//存儲文件路徑
private ArrayList<String> paths = null;
//參數初始化
public MyAdapter(Context context,ArrayList<String> na,ArrayList<String> pa){
names = na;
paths = pa;
directory = BitmapFactory.decodeResource(context.getResources
(),R.drawable.ic_launcher);
file = BitmapFactory.decodeResource(context.getResources
(),R.drawable.ic_launcher);
//縮小圖片
directory = small(directory,0.50f);
file = small(file,0.5f);
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return names.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return names.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (null == convertView){
convertView = inflater.inflate(R.layout.file, null);
holder = new ViewHolder();
holder.text = (TextView)convertView.findViewById(R.id.textView);
holder.image = (ImageView)convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
}
else {
holder = (ViewHolder)convertView.getTag();
}
File f = new File(paths.get(position).toString());
if (names.get(position).equals("@1")){
holder.text.setText("/");
holder.image.setImageBitmap(directory);
}
else if (names.get(position).equals("@2")){
holder.text.setText("..");
holder.image.setImageBitmap(directory);
}
else{
holder.text.setText(f.getName());
if (f.isDirectory()){
holder.image.setImageBitmap(directory);
}
else if (f.isFile()){
holder.image.setImageBitmap(file);
}
else{
System.out.println(f.getName());
}
}
return convertView;
}
private class ViewHolder{
private TextView text;
private ImageView image;
}
private Bitmap small(Bitmap map,float num){
Matrix matrix = new Matrix();
matrix.postScale(num, num);
return Bitmap.createBitmap(map,0,0,map.getWidth(),map.getHeight(),matrix,true);
}
}
}
package com.wenjian;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
public class FileHelper {
private Context context;
private String SDPATH;
private String FILESPATH;
public FileHelper(Context context) {
this.context = context;
SDPATH = Environment.getExternalStorageDirectory().getPath() + "//";
}
/**
* 打開文件
* @param file
*/
public static void openFile(Context context,File file){
//Uri uri = Uri.parse("file://"+file.getAbsolutePath());
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//設置intent的Action屬性
intent.setAction(Intent.ACTION_VIEW);
//獲取文件file的MIME類型
// String type = MIMEType.getMiMeType(file);
//設置intent的data和Type屬性。
// intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
//跳轉
context.startActivity(intent);
}
/**
* 在SD卡上建立文件
*
* @throws IOException
*/
public File creatSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
/**
* 刪除SD卡上的文件
*
* @param fileName
*/
public boolean delSDFile(String fileName) {
File file = new File(SDPATH + fileName);
if (file == null || !file.exists() || file.isDirectory())
return false;
file.delete();
return true;
}
/**
* 在SD卡上建立目錄
*
* @param dirName
*/
public File creatSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
dir.mkdir();
return dir;
}
/**
* 刪除SD卡上的目錄
*
* @param dirName
*/
public boolean delSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
return delDir(dir);
}
/**
* 修改SD卡上的文件或目錄名
* @param fileName
*/
public boolean renameSDFile(String oldfileName, String newFileName) {
File oleFile = new File(oldfileName);
File newFile = new File(newFileName);
return oleFile.renameTo(newFile);
}
/**
* 拷貝SD卡上的單個文件
* @param path
* @throws IOException
*/
public boolean copySDFileTo(String srcFileName, String destFileName,String filename)
throws IOException {
File srcFile = new File(srcFileName);
File destFile = new File(destFileName+"/"+filename);
return copyFileTo(srcFile, destFile);
}
/**
* 拷貝SD卡上指定目錄的全部文件
*
* @param srcDirName
* @param destDirName
* @return
* @throws IOException
*/
public boolean copySDFilesTo(String srcDirName, String destDirName,String filename)
throws IOException {
File srcDir = new File(srcDirName);
File destDir = new File(destDirName+"/"+filename);
return copyFilesTo(srcDir, destDir);
}
/**
* 移動SD卡上的單個文件
*
* @param srcFileName
* @param destFileName
* @return
* @throws IOException
*/
public boolean moveSDFileTo(String srcFileName, String destFileName)
throws IOException {
File srcFile = new File(SDPATH + srcFileName);
File destFile = new File(SDPATH + destFileName);
return moveFileTo(srcFile, destFile);
}
/**
* 移動SD卡上的指定目錄的全部文件
* @param srcDirName
* @param destDirName
* @return
* @throws IOException
*/
public boolean moveSDFilesTo(String srcDirName, String destDirName)
throws IOException {
File srcDir = new File(SDPATH + srcDirName);
File destDir = new File(SDPATH + destDirName);
return moveFilesTo(srcDir, destDir);
}
/*
* 將文件寫入sd卡。如:writeSDFile("test.txt");
*/
// public Output writeSDFile(String fileName) throws IOException {
// File file = new File(SDPATH + fileName);
// FileOutputStream fos = new FileOutputStream(file);
// return new Output(fos);
// }
/*
* 在原有文件上繼續寫文件。如:appendSDFile("test.txt");
*/
// public Output appendSDFile(String fileName) throws IOException {
// File file = new File(SDPATH + fileName);
// FileOutputStream fos = new FileOutputStream(file, true);
// return new Output(fos);
// }
/*
* 從SD卡讀取文件。如:readSDFile("test.txt");
*/
// public Input readSDFile(String fileName) throws IOException {
// File file = new File(SDPATH + fileName);
// FileInputStream fis = new FileInputStream(file);
// return new Input(fis);
// }
/**
* 創建私有文件
*
* @param fileName
* @return
* @throws IOException
*/
public File creatDataFile(String fileName) throws IOException {
File file = new File(FILESPATH + fileName);
file.createNewFile();
return file;
}
/**
* 創建私有目錄
*
* @param dirName
* @return
*/
public File creatDataDir(String dirName) {
File dir = new File(FILESPATH + dirName);
dir.mkdir();
return dir;
}
/**
* 刪除私有文件
*
* @param fileName
* @return
*/
public boolean delDataFile(String fileName) {
File file = new File(FILESPATH + fileName);
return delFile(file);
}
/**
* 刪除私有目錄
*
* @param dirName
* @return
*/
public boolean delDataDir(String dirName) {
File file = new File(FILESPATH + dirName);
return delDir(file);
}
/**
* 更改私有文件名
*
* @param oldName
* @param newName
* @return
*/
public boolean renameDataFile(String oldName, String newName) {
File oldFile = new File(FILESPATH + oldName);
File newFile = new File(FILESPATH + newName);
return oldFile.renameTo(newFile);
}
/**
* 在私有目錄下進行文件複製
*
* @param srcFileName
* : 包含路徑及文件名
* @param destFileName
* @return
* @throws IOException
*/
public boolean copyDataFileTo(String srcFileName, String destFileName)
throws IOException {
File srcFile = new File(FILESPATH + srcFileName);
File destFile = new File(FILESPATH + destFileName);
return copyFileTo(srcFile, destFile);
}
/**
* 複製私有目錄裏指定目錄的全部文件
*
* @param srcDirName
* @param destDirName
* @return
* @throws IOException
*/
public boolean copyDataFilesTo(String srcDirName, String destDirName)
throws IOException {
File srcDir = new File(FILESPATH + srcDirName);
File destDir = new File(FILESPATH + destDirName);
return copyFilesTo(srcDir, destDir);
}
/**
* 移動私有目錄下的單個文件
*
* @param srcFileName
* @param destFileName
* @return
* @throws IOException
*/
public boolean moveDataFileTo(String srcFileName, String destFileName)
throws IOException {
File srcFile = new File(FILESPATH + srcFileName);
File destFile = new File(FILESPATH + destFileName);
return moveFileTo(srcFile, destFile);
}
/**
* 移動私有目錄下的指定目錄下的全部文件
*
* @param srcDirName
* @param destDirName
* @return
* @throws IOException
*/
public boolean moveDataFilesTo(String srcDirName, String destDirName)
throws IOException {
File srcDir = new File(FILESPATH + srcDirName);
File destDir = new File(FILESPATH + destDirName);
return moveFilesTo(srcDir, destDir);
}
/*
* 將文件寫入應用私有的files目錄。如:writeFile("test.txt");
*/
public OutputStream wirteFile(String fileName) throws IOException {
OutputStream os = context.openFileOutput(fileName,
Context.MODE_WORLD_WRITEABLE);
return os;
}
/*
* 在原有文件上繼續寫文件。如:appendFile("test.txt");
*/
// public Output appendFile(String fileName) throws IOException {
// OutputStream os = context.openFileOutput(fileName, Context.MODE_APPEND);
// return new Output(os);
// }
/*
* 從應用的私有目錄files讀取文件。如:readFile("test.txt");
*/
// public Input readFile(String fileName) throws IOException {
// InputStream is = context.openFileInput(fileName);
// return new Input(is);
// }
/********************************************************************************************
**************/
/********************************************************************************************
*************/ /** * 刪除一個文件 * * @param file * @return */ public boolean delFile(File file) { if (file.isDirectory()) return false; return file.delete(); } /** * 刪除一個目錄(能夠是非空目錄) * @param dir */ public boolean delDir(File dir) { if (dir == null || !dir.exists() || dir.isFile()) { return false; } for (File file : dir.listFiles()) { if (file.isFile()) { file.delete(); } else if (file.isDirectory()) { delDir(file);// 遞歸 } } dir.delete(); return true; } /** * 拷貝一個文件,srcFile源文件,destFile目標文件 * @param path * @throws IOException */ public boolean copyFileTo(File srcFile, File destFile) throws IOException { if (srcFile.isDirectory() || destFile.isDirectory()) return false;// 判斷是不是文件 FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); int readLen = 0; byte[] buf = new byte[1024]; while ((readLen = fis.read(buf)) != -1) { fos.write(buf, 0, readLen); } fos.flush(); fos.close(); fis.close(); return true; } /** * 拷貝目錄下的全部文件到指定目錄 * * @param srcDir * @param destDir * @return * @throws IOException */ public boolean copyFilesTo(File srcDir, File destDir) throws IOException { if (!destDir.exists()) { destDir.mkdirs(); } if (!srcDir.isDirectory() || !destDir.isDirectory()) return false;// 判斷是不是目錄 File[] srcFiles = srcDir.listFiles(); for (int i = 0; i < srcFiles.length; i++) { if (srcFiles[i].isFile()) { // 得到目標文件 File destFile = new File(destDir.getPath() + "//" + srcFiles[i].getName()); copyFileTo(srcFiles[i], destFile); } else if (srcFiles[i].isDirectory()) { File theDestDir = new File(destDir.getPath() + "//" + srcFiles[i].getName()); copyFilesTo(srcFiles[i], theDestDir); } } return true; } /** * 移動一個文件 * * @param srcFile * @param destFile * @return * @throws IOException */ public boolean moveFileTo(File srcFile, File destFile) throws IOException { boolean iscopy = copyFileTo(srcFile, destFile); if (!iscopy) return false; delFile(srcFile); return true; } /** * 移動目錄下的全部文件到指定目錄 * @param srcDir * @param destDir * @return * @throws IOException */ public boolean moveFilesTo(File srcDir, File destDir) throws IOException { if (!srcDir.isDirectory() || !destDir.isDirectory()) { return false; } File[] srcDirFiles = srcDir.listFiles(); for (int i = 0; i < srcDirFiles.length; i++) { if (srcDirFiles[i].isFile()) { File oneDestFile = new File(destDir.getPath() + "//" + srcDirFiles[i].getName()); moveFileTo(srcDirFiles[i], oneDestFile); delFile(srcDirFiles[i]); } else if (srcDirFiles[i].isDirectory()) { File oneDestFile = new File(destDir.getPath() + "//" + srcDirFiles[i].getName()); moveFilesTo(srcDirFiles[i], oneDestFile); delDir(srcDirFiles[i]); } } return true; } }