import java.nio.file.Files; //导入方法依赖的package包/类
@Override
public void setFileHiddenAttribute(
String sourceFile,
boolean hidden ) {
sourceFile = IoUtils.normalizeFilePath(sourceFile, osType);
checkFileExistence(new File(sourceFile));
final String errMsg = "Could not " + (hidden
? "set"
: "unset")
+ " the hidden attribute of file '" + sourceFile + "'";
if (OperatingSystemType.getCurrentOsType().isWindows()) {
try {
Path path = Paths.get(sourceFile);
DosFileAttributes attr;
attr = Files.readAttributes(path, DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
boolean goHidden = attr.isHidden();
if (!hidden && goHidden) {
Files.setAttribute(path, "dos:hidden", false, LinkOption.NOFOLLOW_LINKS);
} else if (hidden && !goHidden) {
Files.setAttribute(path, "dos:hidden", true, LinkOption.NOFOLLOW_LINKS);
}
} catch (IOException e) {
throw new FileSystemOperationException(errMsg, e);
}
} else if (OperatingSystemType.getCurrentOsType().isUnix()) {
// a '.' prefix makes the file hidden
String filePath = IoUtils.getFilePath(sourceFile);
String fileName = IoUtils.getFileName(sourceFile);
if (hidden) {
if (fileName.startsWith(".")) {
log.warn("File '" + sourceFile + "' is already hidden. No changes are made!");
return;
} else {
fileName = "." + fileName;
}
} else {
if (!fileName.startsWith(".")) {
log.warn("File '" + sourceFile + "' is already NOT hidden. No changes are made!");
return;
} else {
fileName = fileName.substring(1);
}
}
renameFile(sourceFile, filePath + fileName, false);
} else {
throw new FileSystemOperationException(errMsg + ": Unknown OS type");
}
}