Copier tout le contenu du répertoire dans un autre répertoire? [dupliquer]
cette question a déjà une réponse ici:
méthode pour copier le contenu d'un répertoire entier dans un autre répertoire en java ou groovy?
10 réponses
Copie un répertoire entier vers un nouvel emplacement préserver le fichier date. Cette méthode copie de la répertoire spécifié et tous ses enfants répertoires et fichiers vers les fichiers spécifiés destination. La destination est l' nouvel emplacement et le nom de l' répertoire.
le répertoire de destination est créé si elle n'existe pas. Si l' le répertoire de destination existait, alors cette méthode fusionne la source avec la destination, avec la source prendre préséance.
pour ce faire, voici l'exemple de code
String source = "C:/your/source";
File srcDir = new File(source);
String destination = "C:/your/destination";
File destDir = new File(destination);
try {
FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
e.printStackTrace();
}
voici un exemple d'utilisation de JDK7.
public class CopyFileVisitor extends SimpleFileVisitor<Path> {
private final Path targetPath;
private Path sourcePath = null;
public CopyFileVisitor(Path targetPath) {
this.targetPath = targetPath;
}
@Override
public FileVisitResult preVisitDirectory(final Path dir,
final BasicFileAttributes attrs) throws IOException {
if (sourcePath == null) {
sourcePath = dir;
} else {
Files.createDirectories(targetPath.resolve(sourcePath
.relativize(dir)));
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
Files.copy(file,
targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
}
Pour utiliser le visiteur ne la suit
Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));
Si vous préférez simplement inline tout (pas trop efficace si vous l'utilisez souvent, mais bon pour les p'tites vites)
final Path targetPath = // target
final Path sourcePath = // source
Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(final Path dir,
final BasicFileAttributes attrs) throws IOException {
Files.createDirectories(targetPath.resolve(sourcePath
.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
Files.copy(file,
targetPath.resolve(sourcePath.relativize(file)));
return FileVisitResult.CONTINUE;
}
});
avec Groovy, vous pouvez leverage Ant à faire:
new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
fileset( dir:'/path/to/src/folder' )
}
AntBuilder fait partie de la distribution et de la liste des importations automatiques, ce qui signifie qu'il est directement disponible pour tout code groovy.
public static void copyFolder(File source, File destination)
{
if (source.isDirectory())
{
if (!destination.exists())
{
destination.mkdirs();
}
String files[] = source.list();
for (String file : files)
{
File srcFile = new File(source, file);
File destFile = new File(destination, file);
copyFolder(srcFile, destFile);
}
}
else
{
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(source);
out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0)
{
out.write(buffer, 0, length);
}
}
catch (Exception e)
{
try
{
in.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
out.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
- Utiliser Apache FileUtils.répertoire
- écrire votre propre p. ex. ce type fournit exemple de code .
- Java 7: jetez un oeil à java.nio.fichier.Dossiers .
Ni L'Un Ni L'Autre FileUtils.copyDirectory () nor réponse D'Archimedes attributs du répertoire de copie (propriétaire de fichier, permissions, temps de modification, etc.).
https://stackoverflow.com/a/18691793/14731 fournit une solution complète JDK7 qui fait précisément cela.
C'est mon morceau de code Groovy. Testé.
private static void copyLargeDir(File dirFrom, File dirTo){
// creation the target dir
if (!dirTo.exists()){
dirTo.mkdir();
}
// copying the daughter files
dirFrom.eachFile(FILES){File source ->
File target = new File(dirTo,source.getName());
target.bytes = source.bytes;
}
// copying the daughter dirs - recursion
dirFrom.eachFile(DIRECTORIES){File source ->
File target = new File(dirTo,source.getName());
copyLargeDir(source, target)
}
}
avec l'arrivée de Java NIO, ci-dessous est une solution possible aussi
Avec Java 9:
private static void copyDir(String src, String dest, boolean overwrite) {
try {
Files.walk(Paths.get(src)).forEach(a -> {
Path b = Paths.get(dest, a.toString().substring(src.length()));
try {
if (!a.toString().equals(src))
Files.copy(a, b, overwrite ? new CopyOption[]{StandardCopyOption.REPLACE_EXISTING} : new CopyOption[]{});
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
//permission issue
e.printStackTrace();
}
}
Avec Java 7:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Path sourceParentFolder = Paths.get("/sourceParent");
Path destinationParentFolder = Paths.get("/destination/");
try {
Stream<Path> allFilesPathStream = Files.walk(sourceParentFolder);
Consumer<? super Path> action = new Consumer<Path>(){
@Override
public void accept(Path t) {
try {
String destinationPath = t.toString().replaceAll(sourceParentFolder.toString(), destinationParentFolder.toString());
Files.copy(t, Paths.get(destinationPath));
}
catch(FileAlreadyExistsException e){
//TODO do acc to business needs
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
allFilesPathStream.forEach(action );
} catch(FileAlreadyExistsException e) {
//file already exists and unable to copy
} catch (IOException e) {
//permission issue
e.printStackTrace();
}
}
}
si vous êtes ouvert à l'utilisation d'une bibliothèque de tiers, consultez javaxt-core . Le javaxt.io.La classe de répertoire peut être utilisée pour copier des répertoires comme celui-ci:
javaxt.io.Directory input = new javaxt.io.Directory("/source");
javaxt.io.Directory output = new javaxt.io.Directory("/destination");
input.copyTo(output, true); //true to overwrite any existing files
Vous pouvez également fournir un filtre de fichier pour spécifier les fichiers que vous souhaitez copier. Il y a d'autres exemples ici: