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);
8
  • 1
    Is that all code, where is your rename of the file? Commented Mar 14, 2019 at 13:39
  • @runefist didnt thought there was a point adding that, so i just added the step as a comment Commented Mar 14, 2019 at 13:40
  • Why don't you create a new filename? Commented Mar 14, 2019 at 13:40
  • @reporter what do you mean? create a filename how? and do what with it? Commented Mar 14, 2019 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? Commented Mar 14, 2019 at 13:58

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

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 okay.
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 ?
See copy - one can leave out the vararg copy options, or do Files.copy(file, copiedFile, StandardCopyOption.REPLACE_EXISTING); The right java.nio.file.Files class?
Yes, my automatic pilot leaves me also at odds regularly.
|
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();
    }
}

4 Comments

but what if the file is a pdf, doc or docx? how is the format going to apply on that?
Well you can write byte by byte so I suppose that should work
but that would ruin the format of the text inside of it, in case of a docx i guess. it is very important that the files are not to be altered
well if you write on the byte level the formatting should be unchanged, i also added an exmaple
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();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.