neopablo2000
neopablo2000

Reputation: 169

Java Path Files.copy rename if exists

just a simple question, with a hard (for me) to find answer :D. Here is my code (im going to try to translate the spanish part):

File carpetanueva = new File("C:"+File.separator+"sistema" + File.separator +
     fechasal+File.separator+doc);
carpetanueva.mkdirs();      
carpetanueva.setWritable(true);
rutadestino = ("c:"+File.separator+"sistema" + 
     File.separator + fechasal+File.separator + 
     doc+File.separator+"imagen.jpg");

//realizo la copia de la imagen desde el jfilechooser a su destino:
Path desde = Paths.get(rutaorigen);
Path hacia = Paths.get(rutadestino);

try {
    Files.copy(desde, hacia);
    JOptionPane.showMessageDialog(null, 
            "Se adjunto la planilla de ambulancia correctamente");          
} catch (IOException e) {
    JOptionPane.showMessageDialog(null, "error: "+e.getLocalizedMessage());
}

I get "rutaorigen" (frompath) from a JFileChooser. And I create "rutadestino" (topath) by using some variables so this way i can give an order. The problem is.. .if directories and the file "imagen.jpg" already exists, it gives an error.. (exception).. How can i make to check if image already exists, and if it does, rename the new image to , for example, imagen2? I cant figure out code, because im a newbie, I did a research and couldnt find something like this! Thanks in advance :)

Upvotes: 1

Views: 13067

Answers (4)

blaucuk
blaucuk

Reputation: 165

The code below checks if the file already exists in destination, if it does, it appends #1 to file name just before the extension. If that file name also exists, it keeps appending #2,#3,#4... till the file name doesn't exist in destination. Since () and spaces create problems in Unix environment, I used # instead.

You can extend this and do a SUMCHECK if the file in destination with the identical name also has the same content and act accordingly.

Credit goes to johan indra Permana

        String lastEks = file.getName().toString();
        StringBuilder b = new StringBuilder(lastEks);
        File temp = new File(backupDir.toString() + File.separator + file.getName().toString());

        if (file.getName().contains(".")) {
            if(temp.exists()) {
                temp = new File(backupDir.toString() + File.separator + 
                        b.replace(lastEks.lastIndexOf("."), lastEks.lastIndexOf("."),"#1").toString());
            } else {
                temp = new File(backupDir.toString() + File.separator + file.getName().toString());
            }
            b = new StringBuilder(temp.toString());
        } else {
            temp = new File(backupDir.toString() + File.separator + file.getName());
        }

        if (temp.exists()) {
            for (int x=1; temp.exists(); x++) {
                if(file.getName().contains(".")) {
                    temp = new File (b.replace(
                            temp.toString().lastIndexOf("#"),
                            temp.toString().lastIndexOf("."),
                            "#" + x ).toString());
                } else {
                    temp = new File(backupDir.toString() + File.separator
                            + file.getName() + "#" + x );
                }
            }
            Files.copy(file.toPath(), temp.toPath());
        } else {
            Files.copy(file.toPath(), temp.toPath());
        }

Upvotes: 0

Johan
Johan

Reputation: 425

sory late. but my code can help to litle bit.

public void copyFile(File source, File dest) throws IOException,
FileAlreadyExistsException {
    File[] children = source.listFiles();
    if (children != null) {
        for (File child : children) {
            if (child.isFile() && !child.isHidden()) {

                String lastEks = child.getName().toString();
                StringBuilder b = new StringBuilder(lastEks);
                File temp = new File(dest.toString() + "\\"
                        + child.getName().toString());

                if (child.getName().contains(".")) {
                    if (temp.exists()) {
                        temp = new File(dest.toString()
                                + "\\"
                                + b.replace(lastEks.lastIndexOf("."),
                                        lastEks.lastIndexOf("."), " (1)")
                                        .toString());
                    } else {
                        temp = new File(dest.toString() + "\\"
                                + child.getName().toString());
                    }
                    b = new StringBuilder(temp.toString());
                } else {
                    temp = new File(dest.toString() + "\\"
                            + child.getName());
                }
                if (temp.exists()) {
                    for (int x = 1; temp.exists(); x++) {
                        if (child.getName().contains(".")) {
                            temp = new File(b.replace(
                                    temp.toString().lastIndexOf(" "),
                                    temp.toString().lastIndexOf("."),
                                    " (" + x + ")").toString());
                        } else {
                            temp = new File(dest.toString() + "\\"
                                    + child.getName() + " (" + x + ")");
                        }
                    }
                    Files.copy(child.toPath(), temp.toPath());
                } else {
                    Files.copy(child.toPath(), temp.toPath());
                }
            } else if (child.isDirectory()) {
                copyFile(child, dest);
            }
        }
    }
}

features : 1. rename if file exist in the destination. example: document.doc if exist document (1).doc if exist document (2).doc if exist ... 2. copy all file from source (only file) to one folder in destination

Upvotes: 1

fge
fge

Reputation: 121712

OK, here is a quick solution if src is a Path to the file you want to copy, dst a Path to the file you want to write, and newName a Path to the file you want to rename to:

if (Files.exists(dst))
    Files.move(dst, newName);
Files.copy(src, dst);

Note that you can use the methods in Path to facilitate your path building: .resolve(), .resolveSibling(), .relativize().


Edit: here is a function which will return a suitable name given a directory (dir), a base filename baseName and an "extension" (without the dot) extension:

private static Path findFileName(final Path dir, final String baseName,
    final String extension)
{
    Path ret = Paths.get(dir, String.format("%s.%s", baseName, extension));
    if (!Files.exists(ret))
        return ret;

    for (int i = 0; i < Integer.MAX_VALUE; i++) {
        ret = Paths.get(dir, String.format("%s%d.%s", baseName, i, extension));
        if (!Files.exists(ret))
            return ret;
    }
    throw new IllegalStateException("What the...");
}

Upvotes: 6

trentmwillis
trentmwillis

Reputation: 671

I think this link will help How do I check if a file exists?

So for your case, probably do something like:

File toFile = new File(rutadestino);
if (toFile.exists()) {
    // rename file
    toFile.renameTo(new File("newFilePath/newName.jpg"));
} else {
    // do something if file does NOT exist
}

Hope that helps! For more info, also check the Java Docs for File

Upvotes: 3

Related Questions