package com.copy.file;
/**
* @author wainiwann
* Android SD卡文件目錄拷貝操作
*
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Copy_File extends Activity
{
private Button m_btn = null;
private final static String FROMPATH = "/mnt/sdcard/A/";
private final static String TOPATH = "/mnt/sdcard/B/";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
m_btn = (Button)findViewById(R.id.button1);
m_btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(copy(FROMPATH, TOPATH)==0)
{
Toast.makeText(Copy_File.this,"文件拷貝成功。。",20000).show();
}else
{
Toast.makeText(Copy_File.this,"文件拷貝失。。。",20000).show();
}
}
});
}
public int copy(String fromFile, String toFile)
{
//要復(fù)制的文件目錄
File[] currentFiles;
File root = new File(fromFile);
//如同判斷SD卡是否存在或者文件是否存在
//如果不存在則 return出去
if(!root.exists())
{
return -1;
}
//如果存在則獲取當(dāng)前目錄下的全部文件 填充數(shù)組
currentFiles = root.listFiles();
//目標(biāo)目錄
File targetDir = new File(toFile);
//創(chuàng)建目錄
if(!targetDir.exists())
{
targetDir.mkdirs();
}
//遍歷要復(fù)制該目錄下的全部文件
for(int i= 0;i<currentFiles.length;i++)
{
if(currentFiles[i].isDirectory())//如果當(dāng)前項(xiàng)為子目錄 進(jìn)行遞歸
{
copy(currentFiles[i].getPath() + "/", toFile + currentFiles[i].getName() + "/");
}else//如果當(dāng)前項(xiàng)為文件則進(jìn)行文件拷貝
{
CopySdcardFile(currentFiles[i].getPath(), toFile + currentFiles[i].getName());
}
}
return 0;
}
//文件拷貝
//要復(fù)制的目錄下的所有非子目錄(文件夾)文件拷貝
public int CopySdcardFile(String fromFile, String toFile)
{
try
{
InputStream fosfrom = new FileInputStream(fromFile);
OutputStream fosto = new FileOutputStream(toFile);
byte bt[] = new byte[1024];
int c;
while ((c = fosfrom.read(bt)) > 0)
{
fosto.write(bt, 0, c);
}
fosfrom.close();
fosto.close();
return 0;
} catch (Exception ex)
{
return -1;
}
}
}
下次在寫個文件瀏覽器,然后在獲取某一項(xiàng)的長按事件,然后彈出一個Dialog實(shí)現(xiàn)文件操作。