Path
- 对路径而已,路径分隔符,Unix文件系统是”/”,windows是”\”,以根部件开始的路径是绝对路径,否则是相对路径。
- Path表示的是一个目录名序列,其后还可以跟着一个文件名
- API java.nio.file.Paths 7
- static Path get(String first, String …more),通过连接给定的字符串创建一个路径。
- Path resovle(Path other) Path resolve(String other),如果other是绝对路径,那么就返回other;否则,返回通过连接this和other获取的路径
- Path toAbsolutePath() 返回与该路径等价的绝对路径
- Path getParent() 返回父路径,没有父路径,返回null
- Path getFileName 返回该路径的最后一个部件
- Path getRoot() 返回该路径的跟部件,没有返回null
- toFile()从该路径中创建一个File对象
读写文件
Files类可以使普通文件操作更加的快捷。
//读取文件内容
byte[] bytes = Files.readAllBytes(path);
//如果想要将文件当作字符串处理。
String content = new String(bytes, charset);
//如果希望将文件当作行序列读入
List<String> lines = Files.readAllLines(path, charset);
//如果希望写出一个字符到文件
Files.wirte(path, content.getBytes(charset))
- 以上的方法适合中等长度的文件,处理文件的长度比较大,或者是二进制文件,应该是流或者读入器/写出器
InputStream in = Files.newInputStream(path, options);
OutputStream out = Files.newOutputStream(path, options);
Reader in = Files.newBufferedReader(path, charset);
Writer out = Files.newBufferedWriter(path, charset, options);
- 复制一个文件
- Files.copy(fromPath, toPath);
- 移动文件(即复制并删除原文件)
- Files.move(fromPath, toPath);
- 删除文件
- Files.delete(path);
//创建新文件
public static Path createFile(Path path, FileAttribute<?>... attrs)
//创建新目录
public static Path createDirectory(Path dir, FileAttribute<?>... attrs)
//创建临时文件
public static Path createTempFile(Path dir, String prefix,String suffix, FileAttribute<?>... attrs)