当前位置:网站首页>NiO file and folder operation examples
NiO file and folder operation examples
2022-06-22 16:28:00 【The force is with you】
nio Examples of file and folder operations
Count the number of specific files in a folder
public static void main(String[] args) throws IOException {
// Count the number of folders
AtomicInteger dirCount = new AtomicInteger();
// Count the number of file occurrences
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(Paths.get("D:\\soft\\java\\jdk"),new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
dirCount.getAndIncrement();
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String string = file.toString();
if(string.endsWith(".jar")){
fileCount.getAndIncrement();
}
return super.visitFile(file, attrs);
}
});
System.out.println("dir count: "+dirCount);
System.out.println("file count: "+fileCount);
}
Output :
dir count: 136
file count: 724
Delete files and folders
public static void main(String[] args) throws IOException {
Files.walkFileTree(Paths.get("D:\\a"),new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return super.postVisitDirectory(dir, exc);
}
});
}
Multi level file replication
public static void main(String[] args) throws IOException {
String source = "D:\\a";
String target = "D:\\b";
Files.walk(Paths.get(source)).forEach(path->{
String targetName = path.toString().replace(source,target);
if(Files.isDirectory(path)){
try {
Files.createDirectory(Paths.get(targetName));
} catch (IOException e) {
e.printStackTrace();
}
}
else if(Files.isRegularFile(path)){
try {
Files.copy(path,Paths.get(targetName));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
边栏推荐
猜你喜欢
随机推荐
[Shanda conference] acquisition of user media based on webrtc
What is the relationship between CSC securities and qiniu school? Is it safe to open a securities account
nio文件和文件夹操作例子
SLAM十四讲之第6讲--非线性优化
SAP ABAP 对话框编程教程:中的模块池-09
买网红雪糕的我,成了大冤种
首个赛博格人陨落背后:科技与渐冻症的极限赛跑
安全信得过!天翼云数据安全管理平台通过评测
杜老师自建国内不蒜子统计平台
C语言贪吃蛇
浙江创投圈的“半壁江山”,还得是国资
使用stream api替代sql
SAP ABAP data types, operators and editors-02
【山大会议】软件性能优化及bug修复
畅享高性能计算!天翼云HPC解决方案来了
Reddit对LaMDA模型的探讨:并非无状态,采用双重过程,相比它编辑维基百科的方式,有没有感情并不重要
解决mysql远程登录报权限问题
'不敢去怀疑代码,又不得不怀疑代码'记一次网络请求超时分析
过气剧本杀,被露营“复活”
3. Classe abstraite (forme)








