我制作了一个应用程序,其中有一个案例,我想在库中创建一个名为"私人文件夹" 的文件夹(当用户时)点击按钮"创建文件夹")然后编程 - 想要在其中插入图像说" mypic.png" ......任何人都可以帮助plzzz
答案 0 :(得分:0)
您可以在外部存储器中创建目录,如下所示:
File mydir = new File(Environment.getExternalStorageDirectory() + "/privatefolder/");
mydir.mkdirs();
然后您可以用不同的方式将文件保存在其中。这是其中一个您已经有文件路径并且您想将该图像复制到您的文件夹中的一个:
String oldFilePath = "Your old FilePath";
String newFilePath = new File(Environment.getExternalStorageDirectory() + "/privatefolder/" + "Your image name.jpg");
File newFile = copyFile(oldFilePath , newFilePath);
public static File copyFile(String from, String to) {
try {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
int end = from.toString().lastIndexOf("/");
String str1 = from.toString().substring(0, end);
String str2 = from.toString().substring(end+1, from.length());
File source = new File(str1, str2);
File destination = new File(to, str2);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
return destination;
}
} catch (Exception e) {
return null;
}
return null;
}
也不要忘记在清单中添加此权限:
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
编辑:
用于从drawables保存到SD卡:
//first get a bitmap from your image. if your image name is "photo" do it like this
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.photo);
//then creat your directory. and then copy your image (in this code image format is PNG)
File mydir = new File(Environment.getExternalStorageDirectory() + "/privatefolder/");
mydir.mkdirs();
File file = new File(mydir, "photo.PNG");
FileOutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
使用了一些this答案代码。