I'm strugging to rename files with content to SMB using com.hierynomus.smbj
.
Files are generated with content, but after renaming content is gone.
Following implementation renames files:
public void rename(String pathFrom, String pathTo) {
pathFrom = formatPath(pathFrom);
pathTo = formatPath(pathTo);
Set<SMB2ShareAccess> shareAccessSet = new HashSet<>();
shareAccessSet.add(SMB2ShareAccess.FILE_SHARE_READ);
shareAccessSet.add(SMB2ShareAccess.FILE_SHARE_WRITE);
shareAccessSet.add(SMB2ShareAccess.FILE_SHARE_DELETE);
Set<FileAttributes> fileAttributes = new HashSet<>();
fileAttributes.add(FileAttributes.FILE_ATTRIBUTE_NORMAL);
Set<SMB2CreateOptions> createOptions = new HashSet<>();
SMB2CreateDisposition smb2CreateDisposition = SMB2CreateDisposition.FILE_OVERWRITE_IF;
if (isFolder(pathFrom)) {
createOptions.add(SMB2CreateOptions.FILE_DIRECTORY_FILE);
smb2CreateDisposition = SMB2CreateDisposition.FILE_OPEN_IF;
}
else if (isFile(pathFrom)) {
createOptions.add(SMB2CreateOptions.FILE_NON_DIRECTORY_FILE);
}
else {
throw new IllegalArgumentException("Path '" + pathFrom + "' can't be resolved to file nor directory");
}
try (DiskEntry file = this.smbShare.open(pathFrom, of(AccessMask.MAXIMUM_ALLOWED), fileAttributes, shareAccessSet,
smb2CreateDisposition, createOptions)) {
file.rename(pathTo, true);
}
}
Maybe I messed up the attributes and options in smbShare.open
-function?
Hm.. I messed up with properties of SMB2CreateDisposition
.
The solution: smb2CreateDisposition = SMB2CreateDisposition.FILE_OPEN_IF;
instead of smb2CreateDisposition = SMB2CreateDisposition.FILE_OVERWRITE_IF;
The former opens (1.) or creates (2.) the file in question. The latter overwrites the existing file.