[TOC]
文件系统可以通过java.nio.file.FileSystems
这个final类来访问。 Java7中文件IO发送巨大变化,引入新类:
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
Path类
Path类用来表示文件路径和文件。构架Path对象的方法如下,
使用final类Paths中的两个
static
方法Path path = Paths.get("C:/", "Abc"); Path path2 = Path.get("C:\Abc"); URI u = URI.create("file:///C:/Abc/aa"); Path p = Paths.get(u);
FileSystems构造
Path path3 = FileSystems.getDefault().getPath("C:/", "access.log");
File和Path间转换,File与URI转换
File file = new File("C:/my.ini"); Path p1 = file.toPath(); p1.toFile(); file.toURI();
- 创建文件
java
Path target = Paths.get("C:\\mystruff.txt");
try {
if (!Files.exists(target))
Files.createFile(target);
} catch (IOException e) {
e.printStackTrace();
}
Files.newBufferedReader读取文件
try { BufferedReader reader = Files.newBufferedReader(Path.get("C:\\my.ini"), StandardCharsets.UTF_8); String str = null; while((str = reader.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); }
文件写操作
try { BufferedWriter writer = File.newBufferedWriter(Path.get("C:\\my2.ini"), StandardCharsets.UTF_8); writer.write("写操作,测试"); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); }