【发布时间】:2013-08-27 15:43:05
【问题描述】:
我在尝试检索存储卡上保存的图片时遇到了一些问题。
基本上,我在拍摄图像时使用的代码是:
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();
}
我在第一行得到了 nullPointerException,Log.d(TAG, file.getAbsolutePath());
但是,如果我将这一行放在睡眠之后,则不会抛出 nullPointerException。 睡眠必须优于 500 毫秒才能没有任何错误。
我不知道问题出在哪里,但我相信当 FileOutPutStream 操作完成时,智能手机仍在将数据保存在 sd 卡中。如果我让电话一段时间(0.5-1 秒),问题就会消失,因为写入过程已经完成。
我的问题是:
有什么方法可以知道写入操作何时完成?
【问题讨论】:
-
Just before this lines-- 你的意思是Just AFTER these lines吗? -
@PeterK。抱歉,我是说之后。
-
你上面代码中
file变量的类型和值是什么? -
@unluddite file = new File (myDir, imagename);其中 myDir 是我要保存图像的路径的字符串,而 imagename 是图像的名称,例如“image-00001.jpg”
-
您是否复制/粘贴了写出文件的代码? FileOutputStream 类没有将
byte[]作为参数的write()方法。您还可以包含用于尝试读取文件的代码吗?哪一行代码实际上抛出了异常?
标签: java android io nullpointerexception