1

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 :)

Raul Guiu
  • 2,374
  • 22
  • 37
neopablo2000
  • 139
  • 2
  • 2
  • 6
  • Uhmwait, why are you going through `File` objects? If you want to create a `Path` directly, use `Paths.get()` – fge Apr 08 '14 at 15:14
  • Have you considered using an `if` and the method `exists()`? You can read up on it here: http://www.tutorialspoint.com/java/io/file_exists.htm. That might solve your problem. – ViRALiC Apr 08 '14 at 15:19
  • @fge mmm ok!! Thats going to save me code :D. Im really new to java, and a self-learning! Anyway, i keep thinking how to check existence of file, and if so, how to rename it or the new one, so both can be saved in the same directory! Thank you for your comment!! Sorry my english, not english speaker :( – neopablo2000 Apr 08 '14 at 15:21
  • @ViRALiC, thank you!! Reading and trying it out! :) – neopablo2000 Apr 08 '14 at 15:24
  • @neopablo2000 Good, glad to be of help :) – ViRALiC Apr 08 '14 at 15:27

4 Answers4

6

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...");
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • this worked out of the box, thank you very much!! ;-). just one more question to feed my curiosity.. is there a way i can use this method in a FOR cycle? I mean, if imagen.jpg exists, then rename it to imagen2.jpg, but if imagen2.jpg exists, then rename it to imagen3.jpg, and so on! fge.. sorry for waisting your time, and thank you very much, i can consider my question widely answered :) – neopablo2000 Apr 08 '14 at 17:03
  • Thank you very much fge, ViRALiC and trentmwillis for taking time to answer my, perhaps, silly and newbie question :). But i learned a lot today! And i have a lot more to learn! But people like you make this path (not the class ;-)) much more easy for us! keep up the good work! – neopablo2000 Apr 08 '14 at 17:07
  • In a for loop you'll need to test for different names; see edit for a solution – fge Apr 08 '14 at 17:14
  • i think i cant thank you enough!! I really appreciate your help, and this piece of code!! ;-) – neopablo2000 Apr 09 '14 at 17:42
  • Hi! I tried out your code for returning a suitable name, but there is a little problem here: Path ret = Paths.get(dir,String.format("%s.%s", baseName, extension)); it says this method only takes String, String, not Path, String :). – neopablo2000 Apr 11 '14 at 18:38
  • In my example method, `baseName` is a string, not a `Path`! – fge Apr 11 '14 at 19:34
  • dir.resolve(format("%s.%s", baseName, extension)), dir.resolve(format("%s%d.%s", baseName, i, extension)); – Maxple Aug 25 '20 at 12:35
3

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

Community
  • 1
  • 1
trentmwillis
  • 651
  • 4
  • 6
  • Uhm, OP uses Java 7... There is `Files.exists()`. What is more, `File`'s `.exists()` is broken (doesn't take `file.encoding` into account) – fge Apr 08 '14 at 15:41
  • @fge allright, sooo... figuring out how to code it xD – neopablo2000 Apr 08 '14 at 15:46
  • @fge i made my "hacia" path following your advice about paths.get(). I did it this way: Path hacia = Paths.get(System.getProperty("user.home"),"sistema","imagen.jpg"); and in this way, i make my code more portable. The problem is it gives an error.. thinking.. being "user.home" my root folder.. perhaps is a permissions issue? – neopablo2000 Apr 08 '14 at 15:52
  • @fge i catch my error with "IOException e" and "e.getMessage" in a JOptionPane.showMessageDialog. it only show the origin path (i.e: c:\foo\foo.jpg), then this symbol: -> and then the correct destiny path (in my case: c:\documents and settings\pablo\sistema\imagen.jpg) No error message, just that! – neopablo2000 Apr 08 '14 at 16:07
  • That is far from being enough information! At least log the exception on the console or something. The exception class is needed at the very least. Many `FileSystemException`s only have the path name as a message – fge Apr 08 '14 at 16:36
  • @fge well, i dont know how to do that. I removed JOptionPane.showMessageDialog, and only let e.getMessage(); but console shows nothing. So, Ill stick to my former method with File to create my destiny path until i figure out how to debug the error! Thank you very much!! – neopablo2000 Apr 08 '14 at 16:43
  • @neopablo2000 what, don't you have a console to debug? Any decent IDE has one – fge Apr 08 '14 at 16:51
  • @fge hahahaha! yes, i do have one :). Using Eclipse. What i meant was, console doesnt display errors at all. If i catch the error through JOptionPane.showMessageDialog, it shows a windows with what i mentioned before. If i take out JOptionPane and only catch the error, console shows no error, nothing at all. Perhaps my english is playing jokes with me and cant explain myself? :) – neopablo2000 Apr 08 '14 at 16:57
1

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

Johan
  • 207
  • 4
  • 14
0

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());
        }
blaucuk
  • 125
  • 1
  • 10