java-与文件相关
java.nio.file 表示non-blocking 非阻塞io(输入和输出)
一个 Path 对象表示一个文件或者目录的路径,是一个跨操作系统(OS)和文件系统的抽象
java.nio.file.Paths 类包含一个重载方法 static get(),该方法接受一系列 String 字符串或一个统一资源标识符(URI)作为参数,并且进行转换返回一个 Path 对象
文件操作的两个基本组件:
- 文件或者目录的路径;
- 文件本身。
文件和目录路径
path
Path接口 在java.io及java.nio中,是通过File类来访问文件系统(文件和目录都用File类表示),
但是File类不能利用特定文件系统的特性,且性能不高,抛出的异常也太抽象,因此在NIO.2中引入
了Path接口。 Path接口表示的是一个与平台无关的路径(文件和目录都用Path表示)。 Path类中包含了常用的操作路径的方法, getRoot() -Path对象的跟路径 toAbsolutePath() -Path对象的绝对路径 getNameCount() -Path对象里包含的路径数量
Paths工具类
Paths工具类包含了两个返回Path对象的静态方法。
- static Path get(URI uri) 直接通过路径返回Path对象
- static Path get(String first, String...more)通过给出的String字符串组装成一个Path对象
常用方法:
Path getFileName() 将此路径表示的文件或目录的名称返回为 Path对象 //Path toAbsolutePath()返回表示此路径的绝对路径的 Path对象 int getNameCount() 返回路径中的名称元素的数量。 使用endsWith是比较真个路径部分,但是不包含文件的后缀 getRoot()返回此路径的根组分作为 Path对象,或 null如果该路径不具有根组件
static Path get(String first, String... more) 将路径字符串或连接到路径字符串的字符串序列转换为 Path 。
package fileall; import java.nio.file.Path; import java.nio.file.Paths; public class FileDemo1 { public static void main(String[] args) { // 查看系统的os类型 System.out.println(System.getProperty("os.name")); //Path toAbsolutePath()返回表示此路径的绝对路径的 Path对象 Path p = Paths.get("FileDemo1.java").toAbsolutePath(); System.out.println(p); /* 遍历Path对象的时候并不包含根路径,只有starsWith检测才会 int getNameCount() 返回路径中的名称元素的数量。 */ System.out.println("###########################"); for (int i = 0;i <p.getNameCount();i++){ System.out.println(p.getName(i)); } System.out.println("###########################"); /* 使用endsWith是比较真个路径部分,但是不包含文件的后缀 */ System.out.println("ends with .java" + p.endsWith(".java")); System.out.println("###########################"); for (Path pp:p){ System.out.print(pp+":"); System.out.print(p.startsWith(pp)+":"); System.out.println(p.endsWith(pp)+":"); } /* 遍历Path对象的时候并不包含根路径,只有starsWith检测才会 getRoot()返回此路径的根组分作为 Path对象,或 null如果该路径不具有根组件 */ System.out.println("start" + p.getRoot()+" " + p.startsWith(p.getRoot())); } } /* Windows 10 C:\Users\better.quan\Desktop\spring-boot-chapter\fivetwoseven\FileDemo1.java ########################### Users better.quan Desktop spring-boot-chapter fivetwoseven FileDemo1.java ########################### ends with .javafalse ########################### Users:false:false: better.quan:false:false: Desktop:false:false: spring-boot-chapter:false:false: fivetwoseven:false:false: FileDemo1.java:false:true: startC:\ true */
Files常用方法:
static boolean exists(Path path, LinkOption... options) 测试文件是否存在 static boolean isDirectory(Path path, LinkOption... options) 测试文件是否是目录。 static boolean isExecutable(Path path) 测试文件是否可执行 static boolean isReadable(Path path) 测试文件是否可读。 static boolean isRegularFile(Path path, LinkOption... options) 测试文件是否是具有不透明内容的常规文件。 static boolean isWritable(Path path) 测试文件是否可写 static boolean notExists(Path path, LinkOption... options)测试此路径所在的文件是否不存在。 static FileStore getFileStore(Path path) 返回表示文件所在文件存储区的 FileStore static FileTime getLastModifiedTime(Path path, LinkOption... options) 返回文件的上次修改时间。 static UserPrincipal getOwner(Path path, LinkOption... options) 返回文件的所有者。 static String probeContentType(Path path) 探测文件的内容类型。
public class FileDemo1 { public static void main(String[] args) throws IOException { System.out.println(System.getProperty("os.name")); Path p = Paths.get("src/FileDemo1.java").toAbsolutePath(); System.out.println(p); System.out.println(Files.exists(p)); System.out.println(Files.isDirectory(p)); System.out.println(Files.isExecutable(p)); System.out.println(Files.isReadable(p)); System.out.println(Files.isRegularFile(p)); System.out.println(Files.isWritable(p)); System.out.println(Files.notExists(p)); System.out.println(Files.isHidden(p)); System.out.println(Files.size(p)); System.out.println(Files.getFileStore(p)); System.out.println(Files.getLastModifiedTime(p)); System.out.println(Files.getOwner(p)); System.out.println(Files.probeContentType(p)); } } /* Windows 10 C:\Users\better.quan\Desktop\spring-boot-chapter\fivetwoseven\src\FileDemo1.java true false true true true true false false 1118 Windows (C:) 2020-06-01T02:09:12.383984Z BUILTIN\Administrators (Alias) null */
Paths的增减修改
Path |
relativize(Path other)
构造此路径和给定路径之间的相对路径。
|
public class DEmo11 { public static void main(String[] args) { System.out.println(System.getProperty("os.name")); Path p = Paths.get("src/FileDemo1.java").toAbsolutePath(); System.out.println(p); Path b = Paths.get("fivewoseven").toAbsolutePath(); System.out.println(b); Path c =p.relativize(b); System.out.println(c); } } /* Windows 10 C:\Users\better.quan\Desktop\spring-boot-chapter\fivetwoseven\src\FileDemo1.java C:\Users\better.quan\Desktop\spring-boot-chapter\fivetwoseven\fivewoseven ..\..\fivewoseven */
Path |
resolve(Path other)
根据这条路径解决给定的路径。
|
/* 等于在路径后面加上 */ public class DEmo11 { public static void main(String[] args) { System.out.println(System.getProperty("os.name")); Path p = Paths.get("FileDemo1.java"); System.out.println(p); Path b = Paths.get("fivewoseven").toAbsolutePath(); System.out.println(b); Path c =b.resolve(p); System.out.println(c); } } /* Windows 10 FileDemo1.java C:\Users\better.quan\Desktop\spring-boot-chapter\fivetwoseven\fivewoseven C:\Users\better.quan\Desktop\spring-boot-chapter\fivetwoseven\fivewoseven\FileDemo1.java */
static Path createFile(Path path, FileAttribute<?>... attrs)创建一个新的和空的文件,如果该文件已存在失败。 产生异常:java.nio.file.FileAlreadyExistsException static Path createDirectories(Path dir, FileAttribute<?>... attrs) 首先创建所有不存在的父目录来创建目录。 static Path createDirectory(Path dir, FileAttribute<?>... attrs)创建一个新的目录。
public class DEmo11 { public static void main(String[] args) throws IOException { System.out.println(System.getProperty("os.name")); Path p = Paths.get("quan.java"); System.out.println(p); // Files.createFile(p);//创建新的文件,按照path,默认是项目路径下 Path dir_P = Paths.get("AAA"); Path dir_PM = Paths.get("CCC/BBB"); // 创建新目录,一级,默认是项目目录 Files.createDirectory(dir_P); // 创建多级目录,默认是项目目录 Files.createDirectories(dir_PM); } }
static Path |
createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs)
在指定的目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称
|

static Path |
createTempDirectory(String prefix, FileAttribute<?>... attrs)
在默认临时文件目录中创建一个新目录,使用给定的前缀生成其名称
|
临时木只有前缀没有后缀
文件系统:
abstract Iterable<FileStore> |
getFileStores()
返回一个对象,以遍历底层文件存储。
|
abstract Iterable<Path> |
getRootDirectories()
返回一个对象来遍历根目录的路径
|
abstract String |
getSeparator()
返回名称分隔符,表示为字符串。
|
abstract boolean |
isOpen()
告诉这个文件系统是否打开。
|
abstract boolean |
isReadOnly()
告诉这个文件系统是否只允许只读访问其文件存储。
|
abstract FileSystemProvider |
provider()
返回创建此文件系统的提供程序。
|
abstract Set<String> |
supportedFileAttributeViews()
返回 FileSystem支持的文件属性视图的一组
FileSystem 。 |
public class DEmo11 { public static void main(String[] args) throws IOException { FileSystem fs = FileSystems.getDefault(); System.out.println(fs); Path p = Paths.get("stc/DEmo11.java").toAbsolutePath(); System.out.println(p); System.out.println(fs.getFileStores()); System.out.println(fs.getRootDirectories()); System.out.println(fs.getSeparator()); System.out.println(fs.isOpen()); System.out.println(fs.isReadOnly()); System.out.println(fs.provider()); System.out.println(fs.supportedFileAttributeViews()); } } /* sun.nio.fs.WindowsFileSystem@4554617c C:\Users\better.quan\Desktop\spring-boot-chapter\fivetwoseven\stc\DEmo11.java sun.nio.fs.WindowsFileSystem$1@74a14482 [C:\, D:\, E:\] \ true false sun.nio.fs.WindowsFileSystemProvider@1540e19d [owner, dos, acl, basic, user] */
WatchService
注意:只会监视给定的目录,而不是下面的所有内容。如果需要监视整个树目录,必须在整个树的每个子目录上放置一个 Watchservice。
1从 FileSystem 中得到了 WatchService 对象
2注册到路径以及我们感兴趣的项目的变量参数列表中

变量参数列表如下;

文件读写
/* java.nio.file.Files 类中的实用程序将帮助你轻松读写文本和二进制文件。java.nio.file.Files 类中的实用程序将帮助你轻松读写文本和二进制文件。 */
public class FileWR { public static void main(String[] args) throws IOException { // Paths.get 获取Path对象 //使用readAllLines返回的是字符串集合 List<String> lineList =Files.readAllLines(Paths.get("C:\\Users\\better.quan\\Desktop\\spring-boot-chapter\\fivetwoseven\\src\\filetest")); System.out.println(lineList); lineList.stream()//转换为输入流 .filter(line -> !line.startsWith("//"))//过滤注释 .map(line -> line.substring(0,line.length()/2))//截取每行的长度的一班 .forEach(System.out::println); //跳过注释行,其余的内容每行只打印一半 for (String line:lineList ) { line.startsWith("//"); } } }
[one, two, three, //four, five, six, seven, eight, nine, ten]
o
t
th
fi
s
se
ei
ni
t
------------恢复内容结束------------
------------恢复内容结束------------

浙公网安备 33010602011771号