Comment copier un fichier d'un emplacement à un autre emplacement?


Je veux copier un fichier d'un emplacement à un autre emplacement en Java.

Voici ce que j'ai jusqu'à présent:

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
    public static void main(String[] args) {
        File f = new File(
            "D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
        List<String>temp=new ArrayList<String>();
        temp.add(0, "N33");
        temp.add(1, "N1417");
        temp.add(2, "N331");
        File[] matchingFiles = null;
        for(final String temp1: temp){
            matchingFiles = f.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.startsWith(temp1);
                }
            });
            System.out.println("size>>--"+matchingFiles.length);

        }
    }
}

Il ne copie pas le fichier, quelle est la meilleure façon de le faire?

Author: Eric Leschinski, 2013-05-08

4 answers

, Vous pouvez utiliser ce (ou une variante):

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

De plus, je recommanderais d'utiliser File.separator ou / au lieu de \\pour le rendre compatible sur plusieurs systèmes d'exploitation, question/réponse sur ce disponible ici.

Puisque vous ne savez pas comment stocker temporairement des fichiers, jetez un oeil à ArrayList:

List<File> files = new ArrayList();
files.add(foundFile);

Pour déplacer un List de fichiers dans un seul répertoire:

List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
    Files.copy(file.toPath(),
        (new File(path + file.getName())).toPath(),
        StandardCopyOption.REPLACE_EXISTING);
}
 77
Author: Menno, 2017-05-23 11:55:09

Utilisation du flux

private static void copyFileUsingStream(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 {
        is.close();
        os.close();
    }
}

Utilisation du canal

private static void copyFileUsingChannel(File source, File dest) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destChannel = new FileOutputStream(dest).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
       }finally{
           sourceChannel.close();
           destChannel.close();
       }
}

Utiliser Apache Commons IO lib:

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}

Utilisation de la classe de fichiers Java SE 7:

private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

Test de performance:

    File source = new File("/Users/pankaj/tmp/source.avi");
    File dest = new File("/Users/pankaj/tmp/dest.avi");


    //copy file conventional way using Stream
    long start = System.nanoTime();
    copyFileUsingStream(source, dest);
    System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));

    //copy files using java.nio FileChannel
    source = new File("/Users/pankaj/tmp/sourceChannel.avi");
    dest = new File("/Users/pankaj/tmp/destChannel.avi");
    start = System.nanoTime();
    copyFileUsingChannel(source, dest);
    System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));

    //copy files using apache commons io
    source = new File("/Users/pankaj/tmp/sourceApache.avi");
    dest = new File("/Users/pankaj/tmp/destApache.avi");
    start = System.nanoTime();
    copyFileUsingApacheCommonsIO(source, dest);
    System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));

    //using Java 7 Files class
    source = new File("/Users/pankaj/tmp/sourceJava7.avi");
    dest = new File("/Users/pankaj/tmp/destJava7.avi");
    start = System.nanoTime();
    copyFileUsingJava7Files(source, dest);
    System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));

RÉSULTATS:

/*
 * File copy:
 * Time taken by Stream Copy            = 44582575000
 * Time taken by Channel Copy           = 104138195000
 * Time taken by Apache Commons IO Copy = 108396714000
 * Time taken by Java7 Files Copy       = 89061578000
 */

Lien:

Http://www.journaldev.com/861/4-ways-to-copy-file-in-java

 53
Author: Alexander Pfeif, 2015-09-18 13:12:18
  public static void copyFile(File oldLocation, File newLocation) throws IOException {
        if ( oldLocation.exists( )) {
            BufferedInputStream  reader = new BufferedInputStream( new FileInputStream(oldLocation) );
            BufferedOutputStream  writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
            try {
                byte[]  buff = new byte[8192];
                int numChars;
                while ( (numChars = reader.read(  buff, 0, buff.length ) ) != -1) {
                    writer.write( buff, 0, numChars );
                }
            } catch( IOException ex ) {
                throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
            } finally {
                try {
                    if ( reader != null ){                      
                        writer.close();
                        reader.close();
                    }
                } catch( IOException ex ){
                    Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() ); 
                }
            }
        } else {
            throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
        }
    }  
 5
Author: Quamber Ali, 2013-09-09 06:31:22

Utilisez les nouvelles classes de fichiers Java dans Java >=7.

Créez la méthode ci-dessous et importez les bibliothèques nécessaires.

public static void copyFile( File from, File to ) throws IOException {
    Files.copy( from.toPath(), to.toPath() );
} 

Utilisez la méthode créée comme ci-dessous dans main:

File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);

try {
        copyFile(dirFrom, dirTo);
} catch (IOException ex) {
        Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}

NB:- fileFrom est le fichier que vous souhaitez copier dans un nouveau fichier fileTo dans un autre dossier.

Crédits - @Scott: Moyen concis standard de copier un fichier en Java?

 3
Author: Amimo Benja, 2017-05-23 12:02:47