1. 得到存储设备的目录:/SDCARD(一般情况下)
SDPATH=Environment.getExternalStorageDirectory()+"/";
2. 判断SD卡上的文件夹是否存在:通过File对象的exists()方法。
/**
* 判断文件是否已经存在;
*
/
public boolean checkFileExists(String filepath) {
File file=new File(SDPATH+filepath);
return file.exists();
}
3.在SD卡上创建目录:通过File对象的mkdir()方法实现。
/*
* 在SD卡上创建目录;
*/
public File createDIR(String dirpath) {
File dir=new File(SDPATH+dirpath);
dir.mkdir();
return dir;
}
4.在SD卡上创建文件:通过File对象的createNewFile()方法实现。
/*
* 在SD卡上创建文件;
*/
public File createFile(String filepath) throws IOException{
File file=new File(SDPATH+filepath);
file.createNewFile();
return file;
}
5.将InputStream字节流写入到SD卡文件中。
/**
* 将一个InputStream中的数据写入至SD卡中
*/
public File writeStreamToSDCard(String dirpath,String filename,InputStream input) {
File file = null;
OutputStream output=null;
try {
//创建目录;
createDIR(dirpath);
//在创建 的目录上创建文件;
file = createFile(dirpath+filename);
output=new FileOutputStream(file);
byte[]bt=new byte[4*1024];
while (input.read(bt)!=-1) {
output.write(bt);
}
//刷新缓存,
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try{
output.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
6. 访问的权限:
需在AndroidManifest中加上:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
判断SD卡是否插入
Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
获得sd卡根目录
File skRoot = Environment.getExternalStorageDirectory();
获得私有根目录
File fileRoot = Context.getFilesDir()+"";
确定或获得文件夹和文件路径
String path = File.getPath();//相对
String path = File.getAbsoultePath();//绝对
获得文件或文件夹的父目录
String parentPath = File.getParent()
获得文件或文件夹的名称:
String Name = 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:允许其他应用程序写入,会覆盖原数据。
/*** 保存文件
* @param fileName
* @param fileContent
* @throws Exception*/
public void save(String fileName, String fileContent) throws Exception {
// Activity的父类的父类就是context,context与其他框架中的context相同为我们以供了一些核心操作工具。
FileOutputStream fileOutputStream = this.context.openFileOutput(
fileName, Context.MODE_PRIVATE);
fileOutputStream.write(fileContent.getBytes());
}
/**
* 读取文件
*
* @param fileName
* @return
* @throws Exception
*/
public String read(String fileName) throws Exception {
FileInputStream fileInputStream = this.context.openFileInput(fileName);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(buffer)) > 0) {
byteArray.write(buffer, 0, len);
};
return byteArray.toString();
}
}