当我尝试在SD卡上检索已保存的图片时,我遇到了一些问题。
基本上,拍摄图像时我使用的代码是:
if(now==null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
now = sdf.format(new Date());
}
myDirVids=new File(Environment.getExternalStorageDirectory()+"/TimelapseVideos");
if(!myDirVids.exists()){
myDirVids.mkdirs();
}
myDirPhotos=new File(Environment.getExternalStorageDirectory()+"/TimelapsePhotos");
if(!myDirPhotos.exists()){
myDirPhotos.mkdirs();
}
myDir=new File(myDirPhotos+"/timelapse"+now);
myDir.mkdirs();
DecimalFormat decimalFormat = new DecimalFormat("00000");
imagename = "Image-"+ decimalFormat.format(num) +".jpg";
file = new File (myDir, imagename);
if (file.exists ()) file.delete ();
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在这一行之后,我尝试检索保存的图像,并且我得到一个NullPointerException,因为它似乎不可用:
Log.d(TAG, file.getAbsolutePath());
Log.d(TAG, imagename);
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
我在第一行Log.d(TAG, file.getAbsolutePath());
但是如果我在睡眠后放入这一行,则不会抛出nullPointerException。 睡眠必须优于500毫秒才能没有任何错误。
我不知道问题出在哪里,但我相信当FileOutPutStream操作完成时,智能手机仍在将数据保存在SD卡中。如果我让电话花了一些时间(0.5-1s),问题就会消失,因为写作过程已经完成。
我的问题是:
有什么方法可以知道写作操作何时结束?
答案 0 :(得分:1)
要检查文件是否存在,您可以执行 -
File file = new File(getExternalCacheDirectory(), YOUR_FILE_NAME);
if (file.exists()) {
// Exists
} else {
// Doesn't exist
}
此外,您可以使用MediaScannerConnection扫描文件。
答案 1 :(得分:1)
好的,我终于解决了我的问题。
正如我所说,当我尝试访问刚刚保存的图像时,我收到了NullPointerException。 保存后(以及500ms内)“file”变量为空(由于某种原因,我不知道)。
所以我只是添加了这一行,以便知道文件何时不为空:
while(file==null){}
//retrieve file
感谢您的时间。