gpt4 book ai didi

android - 无法写入 SD 卡

转载 作者:行者123 更新时间:2023-11-29 16:02:11 27 4
gpt4 key购买 nike

我的应用程序允许用户拍照,我希望将该照片存储在应用程序的外部文件目录中 (getExternalFilesDir(null))。除了对 renameTo() 的调用外,一切正常,此调用返回 false,我不知道为什么。

源文件是:

/storage/extSdCard/DCIM/Camera/20140424_154458.jpg

目标文件是:

/storage/emulated/0/Android/data/com.myapp.myapp/files/20140424_154458.jpg

我还指定了 WRITE_EXTERNAL_STORAGE 权限。

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.action_take_picture)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_REQUEST_CODE);
return true;
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == TAKE_PICTURE_REQUEST_CODE && resultCode == RESULT_OK)
{
File dest = new File(
getExternalFilesDir(null),
new SimpleDateFormat("yyyyMMdd_hhmmss", Locale.getDefault()).format(new Date()) + ".jpg");

File src = new File(convertMediaUriToPath(data.getData()));
if (src.renameTo(dest)) // Always returns false
{
mAdapter.add(dest);
mAdapter.notifyDataSetChanged();
}
}
}

private String convertMediaUriToPath(Uri uri)
{
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();

return path;
}

最佳答案

我以前遇到过这个问题 - 不幸的是,您不能使用 renameTo 在不同挂载点(例如,内部和外部存储)之间移动文件和/或目录。考虑使用不同的文件移动方式,例如此处概述的方式:

http://www.mkyong.com/java/how-to-copy-directory-in-java/

public static void copyFolder(File src, File dest) throws IOException{

if(src.isDirectory()){

//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}

//list all the directory contents
String files[] = src.list();

for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}

}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);

byte[] buffer = new byte[1024];

int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}

in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}

关于android - 无法写入 SD 卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23279472/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com