文件路径的描述
public static void main(String[] args) {
Path filePath = Paths.get("E:\\background.jpg");
String fileName = filePath.getFileName().toString();
System.out.println("文件名:"+fileName);
String parentPath = filePath.getParent().toString();
System.out.println("父路径:"+parentPath);
int fileLevel = filePath.getNameCount();
System.out.println("文件层级:"+fileLevel);
String levelName = filePath.getName(0).toString();
System.out.println("指定层级的文件(夹)名:"+levelName);
String otherFile = filePath.resolveSibling("RF").toString();
System.out.println("同级目录其他文件(夹):"+otherFile);
String absPath = filePath.toAbsolutePath().toString();
System.out.println("文件绝对路径:"+absPath);
}
输出
文件操作
public static void main(String[] args) throws IOException {
Path dirPath = Paths.get("E:\\");
Files.exists(dirPath);
Files.notExists(dirPath);
Files.isDirectory(dirPath);
Files.isRegularFile(dirPath.resolve("background.jpg"));
Files.copy(dirPath.resolve("aaa.txt"), dirPath.resolve("bbb.txt"));
Path filePath = Paths.get("E://test.txt");
Files.readAllLines(filePath, Charset.defaultCharset());
Files.readAllBytes(filePath);
Files.write(filePath, Arrays.asList("line1", "line2"));
Files.write(filePath, new byte[]{});
Files.newBufferedWriter(filePath).write("我是test数据");
Files.newInputStream(filePath);
Files.newOutputStream(filePath);
}
Java 8 Files 文件读写
public static void main(String[] args) throws IOException {
Path filePath=Paths.get("E://demo.txt");
if(!Files.exists(filePath)) {
try {
Files.createFile(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bfw=Files.newBufferedWriter(filePath);
bfw.write("Files类的API:newBufferedWriter");
bfw.flush();
bfw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader bfr=Files.newBufferedReader(filePath);
System.out.println(bfr.readLine());
bfr.close();
} catch (IOException e) {
e.printStackTrace();
}
}