2016-07-05 122 views
5

如何防止在android中的内部存储器中存储两次在galary中选择的相同文件。我尝试使用下面的代码在内部存储器的文件夹中多次复制相同的视频。防止在android的内部存储器中存储两次视频文件

 if (resultCode == RESULT_OK) {   
       Uri uri = data.getData(); 
       new SaveVideoInFolder().execute(uri);    
       try { 
        InputStream is = getContentResolver().openInputStream(uri); 
        File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); 
        File app_directory = new File(storage, "video_choosing");     
        if (!app_directory.exists()) 
         app_directory.mkdirs(); 
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());     
        String filename = String.format("VID_%s.mp4", timestamp); 
        file = new File(app_directory, filename);     
        Toast.makeText(MainActivity.this,file.toString(),Toast.LENGTH_SHORT).show();  

        OutputStream output = new FileOutputStream(file);  
        byte[] buffer = new byte[4096]; 
        int read; 

        while ((read = is.read(buffer)) != -1) 
         output.write(buffer, 0, read); 

        output.flush(); 
        output.close(); 
       } catch (FileNotFoundException e) {     
        Log.e("TAG", "File Not Found", e); 
       } catch (IOException e) {     
        Log.e("TAG", "IOException", e); 
       } 
} 

回答

0
File file = new File(app_directory, filename); 
if(file.exists()){ 
    ... 
} 

else { 
    ... 
} 
+0

我的文件名是唯一的,我用当前时间保存视频文件名,所以超时它不同 – ramya

0

//创建存储目录,如果不存在

if (!file.exists()) { if (!file.mkdirs()) { /* Log.e(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory");*/ return null; }

它只是你检查你的文件存在BT if条件,使目录,如果事实并非如此。

相关问题