Path的简单用法

//1. Path 正常用法
Path path = Paths.get("src/main/resource/zip");
logger.debug(path.toRealPath());
logger.debug(path.toAbsolutePath());
logger.debug(path.getFileName());
logger.debug(path.getParent());
logger.debug(path.getNameCount());
logger.debug(path.getRoot()); path = FileSystems.getDefault().getPath("src/main/resource/zip");
logger.debug(path.toRealPath());
logger.debug(path.toAbsolutePath());
logger.debug(path.getFileName());
logger.debug(path.getParent());
logger.debug(path.getNameCount());
logger.debug(path.getRoot()); //2. Path get(String first, String... more) 用默认的文件系统路径分隔符连接元素
Path path2 = Paths.get("src/main", "resource/zip");
logger.debug(path2.toRealPath());
logger.debug(path2.toAbsolutePath());
logger.debug(path2.getFileName());
logger.debug(path2.getParent());
logger.debug(path2.getNameCount());
logger.debug(path2.getRoot()); //3. resolve(other)
//(1) other 不是绝对路径, 连接this父路径和other
Path mainPath = Paths.get("/main/");
Path completePath = mainPath.resolve("/zip/Json.rar");
logger.debug(completePath.toAbsolutePath()); //(2) other 是绝对路径, 使用other
completePath = mainPath.resolve("D:/AbsolutePath/zip/Json.rar");
logger.debug(completePath.toAbsolutePath()); //4. resolveSibling(other) 得到兄弟路径
//(1) other 不是绝对路径, 连接this父路径和other
mainPath = Paths.get("/main/");
completePath = mainPath.resolveSibling("/zip");
logger.debug(completePath.toAbsolutePath()); //(2) other 是绝对路径, 使用other
completePath = mainPath.resolveSibling("D:/AbsolutePath/zip/Json.rar");
logger.debug(completePath.toAbsolutePath()); //5. relativize() 对this解析, 得到相对于other的 相对路径
mainPath = Paths.get("/main/");
Path relativize = mainPath.relativize(Paths.get("/main/AA/BB/CC"));
logger.debug(relativize); //6. normalize() 移除冗余的..和.
Path normalize = Paths.get("/home/cay/../fred/./myprog").normalize();
logger.debug(normalize); //7. path to file
System.out.println(mainPath.toFile()); //8. file to path
System.out.println(mainPath.toFile().toPath());

Paths辅助类用法

File的简单用法

// 创建文件:
boolean result = new File("textFile.txt").createNewFile(); // 文件重命名:
result = new File("textFile.txt").renameTo(new File("newTextFile.txt")); // 删除文件:
new File("somefile.txt").delete(); // 改变文件属性:
File f = new File("somefile.txt");
f.setReadOnly(); // making the file read only
f.setLastModified(new Date().getTime()); // 获取文件大小:
long length = new File("somefile.txt").length(); // 判断文件是否存在:
boolean status = new File("somefile.txt").exists(); // 移动文件:
boolean success = new File("somefile.txt").renameTo(new File(new File("directoryName"), "new Name")); // 获取绝对路径:
File absPath = new File("somefile.txt").getAbsoluteFile(); // 判断是文件还是目录:
boolean isDirectory = new File("somefile.txt").isDirectory();
System.out.println(isDirectory); // false // 列举目录下文件:
String[] fileResult = new File("users/ege").list(); // 创建目录:
boolean mkdirResult = new File("users/ege").mkdir(); //过滤文件
File file = new File("E:\\core");
String[] list = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".pdf");
}
}); for (String pdfFile : list) {
System.out.println(pdfFile);
} //文件监视器
watchService("E:\\test"); //异步通信
//Asynchronous

Files辅助类用法

//1. 读写文件
//(1) Files.readAllBytes()
String string = new String(Files.readAllBytes(Paths.get("E:\\111.txt")), StandardCharsets.UTF_8);
System.out.println(string);
System.out.println(); //(2) Files.readAllLines()
List<String> strings = Files.readAllLines(Paths.get("E:\\111.txt"), StandardCharsets.UTF_8);
System.out.println(strings);
System.out.println(); //(3) Files.write()
//向文件覆写内容
Files.write(Paths.get("E:\\111.txt"), "File Write Test1".getBytes(StandardCharsets.UTF_8)); //向文件追加内容
Files.write(Paths.get("E:\\111.txt"), "File Write Test2".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); //从另一个文件中拷贝文件(处理的文件比较大, 需要用Buffered等) //java.nio.charset.MalformedInputException: Input length = 1==>GBK
Files.write(Paths.get("E:\\111.txt"), Files.readAllLines(Paths.get("E:\\java.txt"), Charset.forName("GBK")), StandardOpenOption.APPEND); //(4) Files.newInputStream()
try(InputStream newInputStream = Files.newInputStream(Paths.get("E:\\111.txt"));){
byte[] b = new byte[1024];
int hasRead = 0;
while ((hasRead = newInputStream.read(b)) > 0) {
System.out.print(new String(b, 0, hasRead));
}
} //(5) Files.newOutputStream()
try(OutputStream newOutputStream = Files.newOutputStream(Paths.get("E:\\111.txt"));){
newOutputStream.write("第一期面授培训大纲.pdf".getBytes());
newOutputStream.write("2017.07体检报告.pdf".getBytes());
newOutputStream.write("csdn下载文档".getBytes());
} //(6) Files.newBufferedReader()
try(BufferedReader newBufferedReader = Files.newBufferedReader(Paths.get("E:\\111.txt"));){
newBufferedReader.lines().forEach(n->System.out.println(n));
} //(7) Files.newBufferedWriter()
try(BufferedWriter newBufferedWriter = Files.newBufferedWriter(Paths.get("E:\\111.txt"));){
newBufferedWriter.write("时寒冰说:未来二十年,经济大趋势(未来篇) - 时寒冰");
newBufferedWriter.write("时寒冰说:未来二十年,经济大趋势(现实篇)");
} //2. 创建文件
//(1) 创建目录及文件
Path pathA = Paths.get("E:\\FilesTest\\A\\111.txt");
if(Files.notExists(pathA)){
Files.createDirectories(pathA.getParent()); //创建中间目录 //windows下不支持PosixFilePermission来指定rwx权限。
// Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-rw-rw-");
// FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(perms); Files.createFile(Paths.get("E:\\FilesTest\\A\\111.txt"));
}
System.out.println(); //(2) 创建临时文件
//建立临时目录
Path tempDirectory = Files.createTempDirectory("temp");
System.out.println(tempDirectory.toAbsolutePath());
Files.deleteIfExists(tempDirectory);
System.out.println(); //建立临时文件
Path createTempFile = Files.createTempFile("temp", ".txt");
System.out.println(createTempFile.toAbsolutePath());
Files.deleteIfExists(createTempFile);
System.out.println(); //3. 复制文件
Files.copy(Paths.get("E:\\111.txt"), pathA, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); Files.copy(pathA, System.out);
System.out.println(); // Path tempPath = Paths.get("E:\\temp.txt");
// Files.copy(System.in, tempPath);
// Files.copy(tempPath, System.out); //4. 移动文件
Path pathB = Paths.get("E:\\FilesTest\\B\\222.txt");
Files.createDirectories(pathB.getParent());
Files.move(pathA, pathB, StandardCopyOption.ATOMIC_MOVE); //5. 文件属性
//(1) Files
Path path = Paths.get("E:\\java.txt");
System.out.println(Files.size(path));
System.out.println(Files.isHidden(path));
System.out.println(Files.isReadable(path));
System.out.println(Files.isWritable(path));
System.out.println(Files.isExecutable(path));
System.out.println(Files.isRegularFile(path));
System.out.println(Files.isDirectory(path));
System.out.println(Files.isSymbolicLink(path));
System.out.println(Files.isSameFile(path, path));
System.out.println(); //Reset Attributes
// PosixFileAttributes readAttributes = Files.readAttributes(source, PosixFileAttributes.class);
// Set<PosixFilePermission> permissions = readAttributes.permissions();
// permissions.clear();
//
// String owner = readAttributes.owner().getName();
// String perms = PosixFilePermissions.toString(permissions);
// permissions.add(PosixFilePermission.OWNER_READ);
// permissions.add(PosixFilePermission.GROUP_READ);
// permissions.add(PosixFilePermission.OTHERS_READ);
// permissions.add(PosixFilePermission.OWNER_READ);
//
// Files.setPosixFilePermissions(source, permissions); //(2) BasicFileAttributes
BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
System.out.println(fileAttributes.creationTime());
System.out.println(fileAttributes.lastAccessTime());
System.out.println(fileAttributes.lastModifiedTime());
System.out.println(fileAttributes.isRegularFile());
System.out.println(fileAttributes.isDirectory());
System.out.println(fileAttributes.isSymbolicLink());
System.out.println(fileAttributes.size());
System.out.println(fileAttributes.fileKey());
System.out.println(); //6. 删除文件
// Files.deleteIfExists(pathA);
// Files.deleteIfExists(pathB); //7. 访问目录中的项
//(1) Files.list() 注意不是Files.lines() 注意list()方法不处理子目录
Path listPath = Paths.get("E:\\core");
Stream<Path> entries = Files.list(listPath);
entries.forEach(n->System.out.println(n.toAbsolutePath()));
System.out.println(); //(2) Files.walk() walk()可以处理子目录, 也可以设置最大访问深度
Stream<Path> walkEntries = Files.walk(listPath, FileVisitOption.FOLLOW_LINKS);
walkEntries.forEach(n->System.out.println(n.toAbsolutePath()));
System.out.println(); //8. 过滤文件
//(1) Files.newDirectoryStream() the glob pattern
DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(listPath, "*.doc");
newDirectoryStream.forEach(n->System.out.println(n.toAbsolutePath()));
System.out.println(); //(2) Files.walkFileTree()
Files.walkFileTree(listPath, new FindDocisitor());
System.out.println(); //(3) 利用FileVisitor接口, 在删除所有文件后, 移除对应目录
Files.walkFileTree(Paths.get("E:\\FilesTest"), new SimpleFileVisitor<Path>(){
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}; public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if(null!=exc){
throw exc;
} Files.delete(dir);
return FileVisitResult.CONTINUE;
};
}); //9.


FileSystems 辅助类用法

处理Zip文件

//1. 建立文件系统
FileSystem fileSystem = FileSystems.newFileSystem(Paths.get("E:\\core.zip"), null); //2. 从zip文件中复制出任意文件
Files.copy(fileSystem.getPath("/111.txt"), Paths.get("E:\\888.txt")); //3. 遍历zip文件系统
Files.walkFileTree(fileSystem.getPath("/"), new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println(file.toAbsolutePath());
return super.visitFile(file, attrs);
}
});

J2SE 8的输入输出--Path/Paths File/Files; FileSystems 类的用法的更多相关文章

  1. Java NIO学习(Path接口、Paths和Files工具类的使用)

    NIO学习:Paths和Files工具类的使用 JDK1.7引入了新的IO操作类.在java.nio.file包下,Java NIO Path接口和Files类. Path接口:Path表示的是一个目 ...

  2. Path;Paths和Files;FileVisitor

    package filet; import java.io.FileOutputStream; import java.nio.file.FileStore; import java.nio.file ...

  3. NIO.2中Path,Paths,Files类的使用

    Java NIO Java NIO概述 Java NIO(New IO(新io),Non-Blocking IO(非阻塞的io))是从Java 1.4版本开始引入的一套新的IO API,可以替代标准的 ...

  4. JAVA基础知识之NIO.2——Path,Paths,Files

    NIO.2 JDK7对NIO进行了重大改进,主要包含以下两方面 新增Path接口,Paths工具类,Files工具类. 这些接口和工具类对NIO中的功能进行了高度封装,大大简化了文件系统的IO编程. ...

  5. Java文件IO操作应该抛弃File拥抱Paths和Files

    Java7中文件IO发生了很大的变化,专门引入了很多新的类: import java.nio.file.DirectoryStream;import java.nio.file.FileSystem; ...

  6. JAVA NIO学习四:Path&Paths&Files 学习

    今天我们将学习NIO 的最后一章,前面大部分涉及IO 和 NIO 的知识都已经讲过了,那么本章将要讲解的是关于Path 以及Paths 和 Files 相关的知识点,以对前面知识点的补充,好了言归正传 ...

  7. Java的Path、Paths和Files

    前言 因为这几天被java.nio的这几个接口和工具类卡到了,就顺便地查了一波文档以及使用方法,这篇其实更像是API的复制粘贴,只不过我在注释里多写了一些output和注意事项,看不惯API的可以选择 ...

  8. java IO流 (九) Path、Paths、Files的使用

    1.NIO的使用说明:>Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的IO API,可以替代标准的Java IO AP.>NI ...

  9. Java NIO Path接口和Files类配合操作文件

    Java NIO Path接口和Files类配合操作文件 @author ixenos Path接口 1.Path表示的是一个目录名序列,其后还可以跟着一个文件名,路径中第一个部件是根部件时就是绝对路 ...

随机推荐

  1. LG1955 [NOI2015]程序自动分析

    题意 题目描述 在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足. 考虑一个约束满足问题的简化版本:假设x1,x2,x3...代表程序中出现的变量,给定n个形如xi=xj或xi≠x ...

  2. C语言指针和操作系统的逻辑地址

    你在进行C语言指针编程中,可以读取指针变量本身值(&操作),实际上这个值就是逻辑地址,它是相对于你当前进程数据段的地址,不和绝对物理地址相干.只有在Intel实模式下,逻辑地址才和物理地址相等 ...

  3. benthos 通过配置文件配置 stream 说明

    stream 模式,我们也可以通过配置文件进行配置 参考配置文件 input: type: http_server buffer: type: memory pipeline: threads: 4 ...

  4. jsfl读取xml,图片,并生成swf

    var newdoc = fl.createDocument(); var doc = fl.getDocumentDOM(); var URI = fl.browseForFolderURL(&qu ...

  5. slf4j-api、slf4j-log4j12、log4j 之间是什么关系?

    slf4j:Simple Logging Facade for Java,为java提供的简单日志Facade.Facade:门面,更底层一点说就是接口.他允许用户以自己的喜好,在工程中通过slf4j ...

  6. JUC集合之 CopyOnWriteArrayList

    CopyOnWriteArrayList介绍 它相当于线程安全的ArrayList.和ArrayList一样,它是个可变数组:但是和ArrayList不同的时,它具有以下特性: 它最适合于具有以下特征 ...

  7. PHP 小技巧之__callStatic魔术方法使用

    使用 PHP 框架时,经常会用到 ORM 模型查询数据库,有没有疑问:为啥有些 ORM 中的静态查询方法,不能通过函数追踪下去呢,很有可能就是使用了 __callStatic 魔术方法的小技巧 这里贴 ...

  8. 电路交换vs分组交换

    电路交换 交换:动态分配传输线路资源. 须经过:建立连接 -> 通话 -> 释放连接. 特点:传输效率低(大部分时间空闲). 分组交换 位于网络边缘的主机&位于网络核心的路由器都是 ...

  9. WCF揭秘学习笔记(4):可信赖会话、会话管理、队列、事务

    可信赖会话 WCF的可信赖会话在绑定层保证消息只会被传输一次,并且保证消息间的顺序.当使用TCP通信时,协议本身保证了可靠性,但它只在两点间的网络 包这个层面提供了这样的保证.WCF的可信赖会话特性保 ...

  10. github for windows 使用

    先在github上申请账号,已有略过. 下载github for windows安装,可以提前安装.NET FRAMEWORK 4.0,否则它会在线下载安装.NET 4. 安装后登录账号,不要急着CL ...