2017-02-08 3 views
0

Задача: Я хочу скопировать выбранные файлы из папки A в папку B. Обе папки находятся во внешнем хранилище.Не удается скопировать файлы в папку

Задача: Он отлично работает, однако в какой-то момент он просто прекращает копирование файлов. Например, если я хочу скопировать 500 файлов, он будет копировать только 110 файлов. Также я заметил, что я не могу копировать видеофайлы, он работает только с изображениями.

Код:

Метод, который я использую для копирования файлов:

private static void makeFileCopy(File source, File dest) throws IOException { 
    InputStream is = null; 
    OutputStream os = null; 
    try { 
     is = new FileInputStream(source); 
     os = new FileOutputStream(dest); 
     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = is.read(buffer)) > 0) { 
      os.write(buffer, 0, length); 
     } 
    }finally { 
     try { 
      if (is != null) 
       is.close(); 
      if (os != null) 
       os.close(); 
     }catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

еще один:

public static void copyFileList(Context context, List<MediaFile> contentList, File mediaFolder) { 
    if (contentList != null) { 
     ContentValues values=new ContentValues(); 
     for (int index=0;index<contentList.size();index++) { 
      MediaFile mediaFile=contentList.get(index); 
      File file = new File(mediaFolder, mediaFile.mediaFile().getName()); 
      boolean isVideo=mediaFile.getType()== MediaFile.Type.VIDEO; 
      if (!file.exists()) { 
       try { 
        if (!file.createNewFile()) { 
         continue; 
        } 
        FileUtils.makeFileCopy(mediaFile.getRealFile().getAbsoluteFile(), file); 

       } catch (IOException ex) { 
        ex.printStackTrace(); 
        continue; 
       } 

       if (isVideo) { 
        values.put(MediaStore.Video.VideoColumns.DATA, file.getAbsolutePath()); 
        context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values); 
       } else { 
        values.put(MediaStore.Images.ImageColumns.DATA, file.getAbsolutePath()); 
        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 
       } 
       values.clear(); 
      } 
     } 
    } 
} 

Спасибо!

+0

Всегда ли он копирует только 110 файлов? Что касается видеофайлов - насколько они велики? Если вы помещаете небольшой видеофайл, его также игнорируют? Вы проверяли журнал на наличие каких-либо исключений? – yakobom

+0

'if (! File.createNewFile()) { continue;'. Удалите эти трески. Это бесполезно. – greenapps

+0

Попробуйте без содержимого ContentValues ​​для теста. – greenapps

ответ

0

Наконец-то я решил эту проблему. Это очень глупая ошибка, которую я сделал.

Я хотел сделать копию файлов, которые у меня уже были в папке назначения, и, проверив if (!file.exists()), он просто не прошел. Итак, у меня есть следующий код:

public static void copyFileList(Context context, List<MediaFile> contentList, File mediaFolder) { 
    if (contentList != null) { 
     ContentValues values=new ContentValues(); 
     for (int index=0;index<contentList.size();index++) { 
      MediaFile mediaFile=contentList.get(index); 
      String fileName=mediaFile.mediaFile().getName(); 

      boolean isVideo=mediaFile.getType()== MediaFile.Type.VIDEO; 
      File file = new File(mediaFolder, fileName); 
      //let a user to decide whether to create a copy of already existing files 
      if(!file.exists()) { 
       file=new File(mediaFolder,uniqueNameFor(fileName)); 
      } 

      if(!file.exists()) { 
       try { 
        FileUtils.makeFileCopy(mediaFile.mediaFile().getAbsoluteFile(), file); 
       } catch (IOException ex) { 
        ex.printStackTrace(); 
        continue; 
       } 

       if (isVideo) { 
        values.put(MediaStore.Video.VideoColumns.DATA, file.getAbsolutePath()); 
        values.put(MediaStore.Video.VideoColumns.MIME_TYPE,mediaFile.getMimeType()); 
        context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values); 
       } else { 
        values.put(MediaStore.Images.ImageColumns.DATA, file.getAbsolutePath()); 
        values.put(MediaStore.Images.ImageColumns.MIME_TYPE,mediaFile.getMimeType()); 
        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 
       } 

      } 
      values.clear(); 
     } 
    } 
} 

Просто создайте уникальное имя файла.

Также я изменить метод копирования:

private static void makeFileCopy(File source, File dest) throws IOException { 
    FileChannel inputChannel = null; 
    FileChannel outputChannel = null; 
    try { 
     inputChannel = new FileInputStream(source).getChannel(); 
     outputChannel = new FileOutputStream(dest).getChannel(); 
     outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); 
    } finally { 
     try { 
      if (inputChannel != null) 
       inputChannel.close(); 
      if (outputChannel != null) 
       outputChannel.close(); 
     }catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

Использование каналов немного быстрее, чем при использовании предыдущего подхода. Посмотрите 4 способа копирования файлов here.

Благодарим за помощь!