How to select a file with JFileChooser and rename it

0

I have a question about renaming a file by selecting JFileChoosr * , but I have found it very difficult to find an answer to my problem.

JFileChooser selecto = (JFileChooser) e.getSource();
    String comand = e.getActionCommand();

    if (comand.equals(JFileChooser.APPROVE_SELECTION)) {

        File rutaActual = selecto.getSelectedFile();

        selecto.getSelectedFile().renameTo(new File(selecto.getSelectedFile(), "nuevoNombre.jpg"));
        System.out.println("Path: " + selecto.getSelectedFile().getPath());

That's the code I have so far and my intention as I said is to rename any selected file, in my case a jpg file

Any help will be welcome.

    
asked by Getsuga Tenshou 09.01.2018 в 21:19
source

1 answer

0

This way you can do it:

  • select the file you want to rename
  • give it a name
  • rename it.

    import javax.swing.*;
    import java.io.File;
    
    public class MiClase {
    
    
        public static void main(String args[]) {
    
    
            JFileChooser jfseleccionador = new JFileChooser();
            jfseleccionador.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            int val = jfseleccionador.showOpenDialog(null);
    
    
            if (val == JFileChooser.OPEN_DIALOG) {
                String pathAbsoluto = jfseleccionador.getSelectedFile().getAbsolutePath();
                String directorioActual = jfseleccionador.getCurrentDirectory().getPath();
    
                JOptionPane.showMessageDialog(null, "Directorio: " + pathAbsoluto+ "path: "+directorioActual);
    
                boolean isArchivoRenombrado = jfseleccionador.getSelectedFile().renameTo(new File(directorioActual + "\text1.png"));//este ultimo puede ser una variable y que la consultes por consola o con un dialogo.
    
                if (isArchivoRenombrado){
                    JOptionPane.showMessageDialog(null, "exito al renombrar archivo");
                }
    
            } else if (val == JFileChooser.CANCEL_OPTION) {
                JOptionPane.showMessageDialog(null, "Proceso cancelado ");
            }
        }
    
    }
    
  • answered by 10.01.2018 / 17:12
    source