Problem when moving a file

0

I have a problem, I want to move all the files in a subfolder to the root, and in case the root folder has a file with the same name, change the name of the file to be moved. Example this is my directory C: /raiz/Hola.txt C: / root / Adiostxt C: /raiz/subCarpeta1/Hola.txt What I want to do is move the Hello.txt of subFolder1 to root, but as in this case, root already contains a Hello.txt, I want to change from subFolder1 / Hello.txt to subFolder1 / Hello - Copy 1.txt and then move it to root. I have the following code, but instead of changing the name of the file in subCarpeta1, I change it to the root.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; 
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Moviator {
public static void move(File origen, File destino) throws IOException {
    if(destino.exists()) 
        destino.renameTo(new  File(getValidName(destino.getAbsolutePath())));


    if(origen.exists()) { 

        InputStream is = new FileInputStream(origen);
        OutputStream os = new FileOutputStream(destino);

        int len;
        byte[] buffer = new byte[1024];

        while( (len = is.read(buffer)) > 0 ) os.write(buffer, 0, len);

        is.close();
        os.close();
        origen.delete();
    }

}


private static String getValidName(String path) {
    int i = 1;
    String[] aux = getData(path);
    String newName = aux[0]+" - Copia "+(i++)+aux[1];

    File newFile = new File(newName);

    if(newFile.exists())
        newName = getValidName(path);

    return newName;
}

private static String[] getData(String filename) {
    //Separo el nombre de la extension
    Pattern p = Pattern.compile("^(.*)(\.[a-zA-Z0-9]{1,})$");
    Matcher m = p.matcher(filename);

    m.matches();

    String[] aux = {m.group(1), m.group(2)};

    return aux;
} 
}
    
asked by bruno Diaz martin 01.08.2018 в 13:27
source

0 answers