1

I have been trying to duplicate a file but change the name of it in the same windows directory but I got not luck.

I cant just copy the file in the same directory because of the windows rule that two files cannot have the same name in the same directory.

I am not allowed to copy it to another directory then rename it, and then move it back in the same directory.

And I don't see any helpful implementation in the File.class.

Tried something like that but it didnt work:

File file = new File(filePath);
File copiedFile = new File(filePath);
//then rename the copiedFile and then try to copy it
Files.copy(file, copiedFile);
Sir. Hedgehog
  • 1,260
  • 3
  • 17
  • 40
  • 1
    Is that all code, where is your rename of the file? – runefist Mar 14 '19 at 13:39
  • @runefist didnt thought there was a point adding that, so i just added the step as a comment – Sir. Hedgehog Mar 14 '19 at 13:40
  • Why don't you create a new filename? – Reporter Mar 14 '19 at 13:40
  • @reporter what do you mean? create a filename how? and do what with it? – Sir. Hedgehog Mar 14 '19 at 13:41
  • 1
    _the windows rule that two files cannot have the same name in the same directory_ I don't think any operating system will let you create two files with the same name in the same directory. Do you want two different files that both have exactly the same contents? – Abra Mar 14 '19 at 13:58
  • @Sir.Hedgehog The value of variable 'filePath' contains also the filename. He is located at the end of the string. To create a new file, you habe to pass a different value. E.g extend the current value with another char. This will create new file with same content and different name. – Reporter Mar 15 '19 at 13:34
  • @reporter can you provide a complete working implementation for your idea? would be more than happy to accept it if it works. – Sir. Hedgehog Mar 15 '19 at 15:17
  • @Sir.Hedgehog It is not nessecary because Joop Eggen has already posted it. – Reporter Mar 15 '19 at 15:23

3 Answers3

2

You could create a new file in the same directory and then just copy the contents of the original file to the duplicate See: Java read from one file and write into another file using methods For more info

you can also use this snippet from https://www.journaldev.com/861/java-copy-file

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}
Pierre
  • 163
  • 1
  • 9
2

An initial attempt would be using Path as suitable:

Path file = Paths.get(filePath);
String name = file.getFileName().toString();
String copiedName = name.replaceFirst("(\\.[^\\.]*)?$", "-copy$0");
Path copiedFile = file.resolveSibling(copiedName);
try {
    Files.copy(file, copiedFile);
} catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
runefist
  • 543
  • 1
  • 8
  • 19
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • did you try this code out? on the start I see it needs a cast to Path from Paths? or am my ide is wrong somehow? – Sir. Hedgehog Mar 14 '19 at 13:51
  • @Sir.Hedgehog okay. – Joop Eggen Mar 14 '19 at 13:55
  • hmmm `The method copy(File, OutputStream) in the type Files is not applicable for the arguments (Path, Path)` are we sure the copy can accept Path ? – Sir. Hedgehog Mar 14 '19 at 13:59
  • See [`copy`](https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html#copy(java.nio.file.Path,java.nio.file.Path,java.nio.file.CopyOption...)) - one can leave out the vararg copy options, or do `Files.copy(file, copiedFile, StandardCopyOption.REPLACE_EXISTING);` ***The right java.nio.file.Files class?*** – Joop Eggen Mar 14 '19 at 14:05
  • i am sorry in behalf of my stupid IDE that auto selected a google import.......... – Sir. Hedgehog Mar 14 '19 at 14:09
  • 1
    Yes, my automatic pilot leaves me also at odds regularly. – Joop Eggen Mar 14 '19 at 14:12
1

@Pierre his code is perfect, however this is what I use so I won't be able to change the extension:

public static void copyWithDifferentName(File sourceFile, String newFileName) {
    if (sourceFile == null || newFileName == null || newFileName.isEmpty()) {
        return;
    }
    String extension = "";
    if (sourceFile.getName().split("\\.").length > 1) {
        extension = sourceFile.getName().split("\\.")[sourceFile.getName().split("\\.").length - 1];
    }
    String path = sourceFile.getAbsolutePath();
    String newPath = path.substring(0, path.length() - sourceFile.getName().length()) + newFileName;
    if (!extension.isEmpty()) {
        newPath += "." + extension;
    }
    try (OutputStream out = new FileOutputStream(newPath)) {
        Files.copy(sourceFile.toPath(), out);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
runefist
  • 543
  • 1
  • 8
  • 19