遍历SD卡:
Java代码 收藏代码packagecom.hilary;importjava.io.File;importandroid.app.Activity;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;/*** @Author: hilary
* @Date: 2011-6-25
*
* 遍历SD卡的文件
**/publicclassMySDextendsActivity {privateButton btn;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {//TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn=(Button) findViewById(R.id.btn1);
btn.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {/*手机的SD卡目录都是在sdcard目录下,所以要得到SD卡的所有文件,就要从/sdcard目录查起*/getAllFiles(newFile("/sdcard"));
}
});
}/*遍历接收一个文件路径,然后把文件子目录中的所有文件遍历并输出来*/privatevoidgetAllFiles(File root){
File files[]=root.listFiles();if(files!=null){for(File f : files){if(f.isDirectory()){
getAllFiles(f);
}else{
System.out.println(f);
}
}
}
}
}
在遍历SD卡的时候需要得到操作SD卡的权限:
Java代码 收藏代码在SD卡中创建文件夹及文件:
Java代码 收藏代码/*创建SD对象 下面的两个对象是一个含意,只是名称不一样*/File file=newFile("/sdcard/text.txt");
File path=newFile("/sdcard/ck");/*判断file文件是否存在,如果不存在则创建file文件*/if(!file.exists()){try{
file.createNewFile();
System.out.println("text.txt 文件创建成功!");
}catch(IOException e) {
e.printStackTrace();
}
}/*判断path文件夹是否存在,如果不存在则创建path文件夹*/if(!path.exists()){
path.mkdirs();
System.out.println("ck 文件夹创建成功");
}
删除及重命名:
Java代码 收藏代码
File file=newFile("/sdcard/text.txt");
File newFile=newFile("/sdcard/text2.txt");
File path=newFile("/sdcard/ck");/*删除文件及文件夹*/if(file.exists()){
file.delete();
}if(path.exists()){
path.delete();
}/*给文件重命名*/if(file.exists()){
file.renameTo(newFile);
}