关于Android file.createNewFile() 方法出现的问题总结
http://my.oschina.net/AlexZhuang/blog/55764
今天在编写向SDcard中,创建文件夹并向其中保存文件的过程中出现个一系列的问题 在此做下总结:
1.首先要注意权限问题
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
01 |
String local_file = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/down/" ; |
03 |
File f = new File(local_file); |
11 |
String local_file = f.getAbsolutePath()+ "/" +filename; |
13 |
File f = new File(local_file); |
17 |
if (!file.createNewFile()) { |
19 |
System.out.println( "File already exists" ); |
23 |
} catch (IOException ex) { |
25 |
System.out.println(ex); |
2.file.createNewFile() 方法出现的问题
会出现No such file ..的问题
需要注意的是:要先对设计的文件路径创建文件夹 , 然后在对文件进行创建
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
File f = new File(path);
f.exists();
if (v.getId() == R.id.btn) {
try {
fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
bm = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(),null, null);
File temp = new File("/mnt/sdcard/mtk/lock.png");
if (!temp.exists()) {
try {
temp.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
outputStream = new FileOutputStream("/mnt/sdcard/mtk/lock.png");
if (outputStream != null) {
dumpBitmap(bm, outputStream);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (v.getId() == R.id.btn02) {
try {
fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
bm = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(),null, null);
File temp = new File("/mnt/sdcard/mtk/wall.png");
if (!temp.exists()) {
try {
temp.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
outputStream = new FileOutputStream("/mnt/sdcard/mtk/wall.png");
if (outputStream != null) {
dumpBitmap(bm, outputStream);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void dumpBitmap(Bitmap bm, OutputStream outputStream2) {
// TODO Auto-generated method stub
bm.compress(Bitmap.CompressFormat.PNG, 100, outputStream2);
}
private static void dumpBitmap(Bitmap b) {
if (b != null) {
java.io.FileOutputStream fos = null;
try {
String filename = android.os.Environment.getExternalStorageDirectory().toString()+"/DCIM/Bitmap["+
android.os.SystemClock.uptimeMillis() + "].png";
fos = new java.io.FileOutputStream(filename);
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (java.io.IOException ex) {
// MINI_THUMBNAIL not exists, ignore the exception and generate one.
} finally {
if (fos != null) {
try {
fos.close();
} catch (java.io.IOException ex) {
}
}
}
}
}