Copy files, change the name and move it to another folder in java

4

I'm doing a program in java where I want to have an order of the images that I'm working with and I want to have a copy of it, change the name and have it in a specific folder. I have the following code.

 JFileChooser fc = new JFileChooser();
        int seleccion = fc.showOpenDialog(this);

//Si el usuario, pincha en aceptar
        if (seleccion == JFileChooser.APPROVE_OPTION) {

            try {
                //Seleccionamos el fichero
                File fichero = fc.getSelectedFile();
                if (fichero.exists()) {
                    File fdest = new File(Paths.get(".").toAbsolutePath().normalize().toString() + "/" + conductor.getDni(), jTextField1.getText() + "." + FilenameUtils.getExtension(fichero.getAbsolutePath()));
                    Files.move(fichero.toPath(), fdest.toPath()); //esta parte del codigo no funciona
//   FileUtils.copyFileToDirectory(fichero, fdest); --> esta parte si me mueve el archivo pero no como necesito exactamente
                    if (fdest.exists()) {
                        Documentacion d = new Documentacion();
                        d.setConductor(conductor);
                        d.setDescripcion(jTextField1.getText());
                        d.setRuta(fdest.getAbsolutePath());
                        DocumentacionJpaController controller = new DocumentacionJpaController(emf);
                        controller.create(d);
                        cargarTabla(conductor);
                    } else {
                        System.out.println("error no se pudo mover");
                    }
                }

            } catch (Exception ex) {
                Logger.getLogger(AddDocumentos.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

FileUtils.copyFileToDirectory works but for example if I have C: / a.jpg and I want to move it to C: /micarpeta/cedula.jpg when executing that instruction the following is created C: /micarpeta/cedula.jpg/a.jpg

    
asked by Sergio Guerrero 16.02.2017 в 20:52
source

4 answers

3

If you do not need the Apache library and you are only going to use it to copy files (you must have it for the solution of @StefanNolde), since Java 1.7 there is a native method to do what you ask:

Files.copy(FileSystems.getDefault().getPath(origen),
       FileSystems.getDefault().getPath(destino),
       StandardCopyOption.REPLACE_EXISTING);

This way you avoid having to include a library to your project if you do not need it.

    
answered by 17.02.2017 / 13:01
source
1

Rename, move, delete or copy a file in Java

Here

The class java.nio.file.Files, implements a series of static methods for file handling operations (files), among which is the move () method.

Using this method, we can write a function that moves a file from one directory to another. The move () method receives a CopyOptions argument, with which we can specify that it overwrites the destination file if it already existed.

package mx.com.softmolina;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 *
 * @author SoftMolina
 */
public class MoverArchivoMove {

    public static void main(String[] args) {

        Path origenPath = FileSystems.getDefault().getPath("C:\carpeta1\ejemplo1.jpg");
        Path destinoPath = FileSystems.getDefault().getPath("C:\carpeta2\ejemplo1.jpg");

        try {
            Files.move(origenPath, destinoPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            System.err.println(e);
        }

    }

}

Copy a file to Java

The class java.nio.file.Files, implements a series of static methods for file handling operations (files), among which is the copy () method.

Using this method, we can write a function that copies a file elsewhere. The copy () method receives a CopyOptions argument, with which we can specify that it overwrites the destination file if it already existed.

package mx.com.softmolina;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author SoftMolina
 */
public class CopiarArchivo {

    static final Logger LOGGER = Logger.getAnonymousLogger();

    public static void copiarArchivo(String origenArchivo, String destinoArchivo) {
        try {
            Path origenPath = Paths.get(origenArchivo);
            Path destinoPath = Paths.get(destinoArchivo);
            //sobreescribir el fichero de destino si existe y lo copia
            Files.copy(origenPath, destinoPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (FileNotFoundException ex) {
            LOGGER.log(Level.SEVERE, ex.getMessage());
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, ex.getMessage());
        }
    }

}
    
answered by 07.03.2017 в 22:17
0

In the case that Java6 or earlier is still used, it can be used as apache.commons

File fuente = new File("ruta/a/fuente.jpg");
File destino = new File("ruta/a/otro/destino.jpg);
FileUtils.copyFile(fuente,destino);

If you use copyFileToDirectory the expected thing happens that Java assumes that destination would be a folder and adds the new name.

    
answered by 16.02.2017 в 21:29
0

Well, I understand that renaming files you can do. Create two objects of type File, the first would be:

 f1 = new File("C:/a.jpg"), 

and the second would be

 f2 = new File("C:/micarpeta/cedula.jpg");

then you would have to rename it:

 f1.renameTo(f2)

I hope it is the solution to your problem.

    
answered by 16.02.2017 в 20:59