//假设是Unix的文件系统
Path absolute = Paths.get("/home", "cat"); //绝对路径
Path relative = Pahts.get("ixenos", "config", "user.properties"); //相对路径
String baseDir = properties.getProperty("base.dir");
//可能获得 /opt/ixenos 或者 C:\Program Files\ixenos
Path basePath = Paths.get(baseDir);
Path workRelative = Paths.get("work");
Path workPath = basePath.resolve(workRelative);
//resolve也可以接受字符串形参
Path workPath = basePath.resolve("work");
Path tempPath = workPath.resolveSibling("temp");
/*
如果workPath是 /opt/ixenos/work
那么将创建 /opt/ixenos/temp
*/
/* pathA为 /home/misty pathB为 /home/ixenos/config 现已pathA对pathB进行相对化操作,将产生冗余路径 */ Path pathC = pathA.relativize(pathB); //此时pathC为 ../ixenos/config /* normalize方法将移除冗余部件 */ Path pathD = pathC.normalize(); //pathD为 /ixenos/config
/* Files提供的简便方法适用于处理中等长度的文本文件 如果要处理的文件长度较大,或者二进制文件,那么还是应该使用经典的IO流 */ //将文件所有内容读入byte数组中 byte[] bytes = Files.readAllBytes(path); //传入Path对象 //之后可以根据字符集构建字符串 String content = new String(bytes, charset); //也可以直接当作行序列读入 List<String> lines = Files.readAllLines(path, charset); //相反,也可以写一个字符串到文件中,默认是覆盖 Files.write(path, content.getBytes(charset)); //传入byte[] //追加内容,根据参数决定追加等功能 Files.write(path, content.getBytes(charset), StandardOpenOption.APPEND); //传入枚举对象,打开追加开关 //将一个行String的集合List写出到文件中 Files.write(path, lines);
//复制 Files.copy(fromPath, toPath); //剪切 Files.move(fromPath, toPath); /* 以上如果toPath已存在,那么操作失败, 如果要覆盖,需传入参数REPLACE_EXISTING 还要复制文件属性,传入COPY_ATTRIBUTES */ Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
//创建新目录,除了最后一个部件,其他必须是已存在的 Files.createDirectory(path); //创建路径中的中间目录,能创建不存在的中间部件 Files.createDirectories(path); /* 创建一个空文件,检查文件存在,如果已存在则抛出异常 而检查文件存在是原子性的,因此在此过程中无法执行文件创建操作 */ Files.createFile(path); //添加前/后缀创建临时文件或临时目录 Path newPath = Files.createTempFile(dir, prefix, suffix); Path newPath = Files.createTempDirectory(dir, prefix);
1、//File类list所有文件
public String[] list() {
SecurityManager security = System.getSecurityManager(); //文件系统权限获取
if (security != null) {
security.checkRead(path);
}
if (isInvalid()) {
return null;
}
return fs.list(this); //底层调用FileSystem的list
}
//FileSystem抽象类的list
//File类中定义fs是由DefaultFileSystem静态生成的
private static final FileSystem fs = DefaultFileSystem.getFileSystem();
//因此我们来看一下DefaultFileSystem类,发现是生成一个WinNtFileSystem对象
class DefaultFileSystem {
/**
* Return the FileSystem object for Windows platform.
*/
public static FileSystem getFileSystem() {
return new WinNTFileSystem();
}
}
//而WinNtFileSystem类继承于FileSystem抽象类,这里我们主要观察它的list(File file)方法
@Override
public native String[] list(File f);
/*我们可以看到这是个native方法,说明list的操作是由操作系统的文件系统控制的,当目录中包含大量的文件时,这个方法的性能将会非常低。
由此为了替代,NIO的Files类设计了newDirectoryStream(Path dir)及其重载方法,将生成Iterable对象(可用foreach迭代)*///~
2、//回调过滤
public String[] list(FilenameFilter filter) { //采用接口回调
String names[] = list(); //调用list所有
if ((names == null) || (filter == null)) {
return names;
}
List<String> v = new ArrayList<>();
for (int i = 0 ; i < names.length ; i++) {
if (filter.accept(this, names[i])) { //回调FilenameFileter对象的accept方法
v.add(names[i]);
}
}
return v.toArray(new String[v.size()]);
}
| [code]staticDirectoryStream<Path>[/code] | [code]newDirectoryStream(Path dir)[/code]
Opens a directory, returning a [code]DirectoryStream[/code] to iterate over all entries in the directory.
|
| [code]staticDirectoryStream<Path>[/code] | [code]newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter)[/code]
Opens a directory, returning a [code]DirectoryStream[/code] to iterate over the entries in the directory.
|
| [code]staticDirectoryStream<Path>[/code] | [code]newDirectoryStream(Path dir, String glob)[/code] |
try(DirectoryStream<Path> entries = Files.newDirectoryStream(dir))
{
for(Path entry : entries)
{
...
}
}
try(DirectoryStream<Path> entries = Files.newDirectoryStream(dir, "*.java")) //
{
...
}
| Glob模式 | 描述 |
|---|---|
| *.txt | 匹配所有扩展名为.txt的文件 |
| *.{html,htm} | 匹配所有扩展名为.html或.htm的文件。{ }用于组模式,它使用逗号分隔 |
| ?.txt | 匹配任何单个字符做文件名且扩展名为.txt的文件 |
| [i].[/i] | 匹配所有含扩展名的文件 |
| C:\Users\* | 匹配所有在C盘Users目录下的文件。反斜线“\”用于对紧跟的字符进行转义 |
| /home/** | UNIX平台上匹配所有/home目录及子目录下的文件。**用于匹配当前目录及其所有子目录 |
| [xyz].txt | 匹配所有单个字符作为文件名,且单个字符只含“x”或“y”或“z”三种之一,且扩展名为.txt的文件。方括号[]用于指定一个集合 |
| [a-c].txt | 匹配所有单个字符作为文件名,且单个字符只含“a”或“b”或“c”三种之一,且扩展名为.txt的文件。减号“-”用于指定一个范围,且只能用在方括号[]内 |
| [!a].txt | 匹配所有单个字符作为文件名,且单个字符不能包含字母“a”,且扩展名为.txt的文件。叹号“!”用于否定 |
/*传入一个FileVisitor子类的匿名对象*/
Files.walkFileTree(dir, new SimpleFileVisitor<Path>()
{
//walkFileTree回调此方法来遍历所有子孙
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException
{
if(attrs.isDirectory()) //自定义的选择,属于业务代码,这和walkFileTree的宗旨(遍历所有子孙成员)无关
System.out.println(path);
return FileVisitResult.CONTINUE;
}
public FileVisitResult visitFileFailed(Path path, IOException exc) throws IOException
{
return FileVisitResult.CONTINUE;
}
});
/*假设zipname是某个ZIP文件的名字*/ FileSystem fs = FileSystems.newFileSystem(Paths.get(zipname), null);
Files.copy(fs.getPath(fileName), targetPath);
FileSystem fs = FileSystems.newFileSystem(Paths.get(fileName), null);
//walkFileTree需要传入一个要被遍历的目录Path,和一个FileVisitor对象
Files.walkFileTree(fs.getPath("/"),
newSimpleFileVisitor<Path>(){
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws Exception{
System.out.println(file);
return FileVisitResult.CONTINUE;
});
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有