1

i try to copy files without their filesystem attributes. there are some readonly only files, but i do not want their copy to be readonly. so i use

Files.copy(src,target,REPLACE_EXISTING);

but... the target gets the readonly attribute without COPY_ATTRIBUTES too. (OS: Win10, Envir: JavaSE17)

Samplecode:

final CopyOption[] c1 = new CopyOption[] {};
final CopyOption[] c2 = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
final CopyOption[] c3 = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES };
    
Files.copy(Paths.get(sourceFileName), Paths.get(targetFileName + "_c1"), c1);
Files.copy(Paths.get(sourceFileName), Paths.get(targetFileName + "_c2"), c2);
Files.copy(Paths.get(sourceFileName), Paths.get(targetFileName + "_c3"), c3);

Result:

f:\TMP\15049011634773449363\LIB__fuelsys_dd_controllerLib__0.0.1\INCLUDES>attrib *
    
AR F:\TMP\1....\LIB__fuelsys_dd_controllerLib__0.0.1\INCLUDES\fuelsys_dd_controller.c_c1
AR F:\TMP\1....\LIB__fuelsys_dd_controllerLib__0.0.1\INCLUDES\fuelsys_dd_controller.c_c2
AR F:\TMP\1....\LIB__fuelsys_dd_controllerLib__0.0.1\INCLUDES\fuelsys_dd_controller.c_c3

I can fix the behavior with

new File(targetFileName).setWritable(true);

but its a bit annoying to have to reset the attribute all the time. I dont want to copy it.

MarioSemo
  • 11
  • 2
  • The [documentation](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html#copy(java.nio.file.Path,java.nio.file.Path,java.nio.file.CopyOption...)) says “File attributes are not required to be copied to the target file,” so while this isn’t technically a bug, I can certainly see how it’s annoying. I don’t see any way to do an attributeless copy in one line of code. (By the way, `Files.setAttribute(targetPath, "dos:readonly", false);` is probably the more reliable way to clear the attribute.) – VGR Jan 14 '22 at 13:29
  • regarding Files.setAttributes : i was afraid that this is Operating System specific ("dos:...") and then my application does not work anymore on Linux and in the Cloud. Am i wrong on this? – MarioSemo Jan 15 '22 at 12:04
  • You are correct. I shouldn’t have assumed you only needed it to run on Windows. File.setWritable is safe on all platforms, while setting a “dos:” attribute would only be safe if `targetPath.getFileSystem().supportedAttributeViews().contains("dos")` returned true. – VGR Jan 15 '22 at 14:11

0 Answers0