<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
public File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
catch (IOException e) {
// Error while creating file
}
return file;
}
/* SD卡是否可写 */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* SD卡是否可读 */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
创建一个公共文件,当程序被卸载时,该文件依然存在
public File getAlbumStorageDir(String albumName) {
//Environment.DIRECTORY_PICTURES为文件夹名称,这里使用的是系统常量
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
创建一个文件,当程序被卸载时,该文件将被删除
public File getAlbumStorageDir(Context context, String albumName) {
//如果没有适合的子目录名称,可以改为调用 getExternalFilesDir() 并传递 null。这将返回外部存储上该应用的专用目录的根目录。
File file = new File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
常规方法
myFile.delete();
如果文件保存在内部存储中,还可以请求 Context 通过调用 deleteFile() 来定位和删除文件:
myContext.deleteFile(fileName);
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/duanymin/article/details/48003455