java中setattribute_Java Files.setAttribute方法代码示例

该代码段展示了如何在不同操作系统下设置或移除文件的隐藏属性。在Windows系统中,它使用`Files.setAttribute`方法修改文件的`dos:hidden`属性;在Unix系统中,通过更改文件名前缀来实现隐藏。如果操作系统不被识别,会抛出异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值