android的文件操作要有权限:
判断SD卡是否插入
Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
获得sd卡根目录
FileskRoot=Environment.getExternalStorageDirectory();
获得私有根目录
FilefileRoot=Context.getFilesDir()+"\";
确定或获得文件夹和文件路径
Stringpath=File.getPath();//相对
Stringpath=File.getAbsoultePath();//绝对
获得文件或文件夹的父目录
StringparentPath=File.getParent()
获得文件或文件夹的名称:
StringName=File.getName();
建立文件或文件夹
File.createNewFile();//建立文件
判断是文件或文件夹
File.isDirectory()
列出文件夹下的所有文件和文件夹名
File[]files=File.listFiles();
修改文件夹和文件名
File.renameTo(dest);
删除文件夹或文件
File.delete();
文件读写操作模式
Context.MODE_PRIVATE:新内容覆盖原内容
Context.MODE_APPEND:新内容追加到原内容后
Context.MODE_WORLD_READABLE:允许其他应用程序读取
Context.MODE_WORLD_WRITEABLE:允许其他应用程序写入,会覆盖原数据。
/***保存文件
*@paramfileName
*@paramfileContent
*@throwsException*/
publicvoidsave(StringfileName,StringfileContent)throwsException{
//Activity的父类的父类就是context,context与其他框架中的context相同为我们以供了一些核心操作工具。
FileOutputStreamfileOutputStream=this.context.openFileOutput(
fileName,Context.MODE_PRIVATE);
fileOutputStream.write(fileContent.getBytes());
}
/**
*读取文件
*
*@paramfileName
*@return
*@throwsException
*/
publicStringread(StringfileName)throwsException{
FileInputStreamfileInputStream=this.context.openFileInput(fileName);
ByteArrayOutputStreambyteArray=newByteArrayOutputStream();
byte[]buffer=newbyte[1024];
intlen=0;
while((len=fileInputStream.read(buffer))>0){
byteArray.write(buffer,0,len);
};
returnbyteArray.toString();
}
}