gpt4 book ai didi

Android 代码不创建文件。找不到这样的文件或目录错误

转载 作者:行者123 更新时间:2023-11-29 19:49:15 24 4
gpt4 key购买 nike

我有以下代码可以将捕获的图像写入 SD 卡

private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");

if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
return null;
}
}

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}

使用方法如下:

public void takePicture(){
i= new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //Open camera
file = Uri.fromFile(getOutputMediaFile());
i.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(i, 100);
}

捕获图像后,将文件路径发送到以下函数:

public void sendForUpload(String uploadUrl, String path){
File dir = Environment.getExternalStorageDirectory();
File imgFile = new File(dir, path);
sendFile(uploadUrl, imgFile);
}
public void sendFile(String uploadUrl, File file){
Log.d(GlobalClass.TAG, "File has arrived here");
Log.d(GlobalClass.TAG, file.toString());
byte[] fileData1 = new byte[(int) file.length()];
FileInputStream fileInputStream;
try{
fileInputStream = new FileInputStream(file);
fileInputStream.read(fileData1);
fileInputStream.close();
}catch (Exception e){
Log.d("Error", e.getMessage());
}
.... // Upload
}

此处的 try block 失败,日志显示错误:

D/Error: /storage/emulated/0/storage/emulated/0/Pictures/AppName/IMG_20160516_120506.jpg: open failed: ENOENT (No such file or directory)

如何将文件读入sendFile()

最佳答案

仔细查看错误中的路径:

/storage/emulated/0/storage/emulated/0/Pictures/AppName/IMG_20160516_120506.jpg

您会注意到 /storage/emulated/0 重复了。

替换:

File dir = Environment.getExternalStorageDirectory();
File imgFile = new File(dir, path);

与:

File imgFile = new File(path);

关于Android 代码不创建文件。找不到这样的文件或目录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37258666/

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