TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
创建Path实例
Path实例包含了指定文件或目录位置的信息,在实例化Path类时,需要指定一个或多个目录或文件名。路径的根目录不是必须的;路径信息可能仅仅是一个目录或文件的名称。最简单的创建Path实例的方式就是使用Paths(注意这里有一个s)类的get方法:
Path p1 = Paths.get("/tmp/foo");
Path p2 = Paths.get(args[0]);
Path p3 = Paths.get("file:///Users/joe/FileTest.java"); Path类接受String或URI作为参数。 获取路径信息
File System一般是树形结构,因此我们可以把Path理解为按顺序存储的一系列的名称(目录名称和文件名称)。目录结构中最高一层的目录名就是序列中 index为0的那一个,目录结构中最低一层的目录名或者文件名就是序列中index为n-1的那一个(这里n是路径中层次的数目)。
Path类提供方法来通过index获取序列中的一个元素或一个子序列。
- import java.nio.file.Paths;
- import java.nio.file.Path;
- public class Test{
- public static void main(String args[]){
- Path path = Paths.get("C:\home\joe\foo"); // Microsoft Windows syntax
- //Path path = Paths.get("/home/joe/foo"); // Solaris syntax
- System.out.println("path.toString()--"+path.toString());
- System.out.println("path.getName(1)--"+path.getName(1));
- System.out.println(path.getName(0));
- System.out.println(path.getNameCount());
- System.out.println(path.subpath(0,2));
- System.out.println(path.getParent());
- System.out.println(path.getRoot());
- }
- }
复制代码 运行:
C:ex>java Test
path.toString()--C:homejoefoo
path.getName(1)--joe
getName(0): home
getNameCount: 3
homejoe
getParent: C:homejoe
getRoot: C:- //java7新特性IO操作Path
-
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.IOException;
- import java.nio.charset.Charset;
- import java.nio.file.FileSystems;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- /**
- * Path是java1.7的nio.file包中的文件
- * 操作的重要切入点,作为基础有必要了解下
- * @author zKF57533
- */
- public class TestPath {
- public static void main(String[] args) {
- //获得path方法一,c:/ex/access.log
- Path path = FileSystems.getDefault().getPath("c:/ex", "access.log");
- System.out.println(path.getNameCount());
- //获得path方法二,用File的toPath()方法获得Path对象
- File file = new File("e:/ex/access.log");
- Path pathOther = file.toPath();
- //0,说明这两个path是相等的
- System.out.println(path.compareTo(pathOther));
- //获得path方法三
- Path path3 = Paths.get("c:/ex", "access.log");
- System.out.println(path3.toString());
-
- //join two paths
- Path path4 = Paths.get("c:/ex");
- System.out.println("path4: " + path4.resolve("access.log"));
- System.out.println("--------------分割线---------------");
- try {
- if(Files.isReadable(path)){
- //注意此处的newBufferedRead的charset参数,如果和所要读取的文件的编码不一致,则会抛出异常
- //java的新特性,不用自己关闭流
- BufferedReader br = Files.newBufferedReader(path, Charset.defaultCharset());
- //new BufferedReader(new FileReader(new File("e:/logs/access.log")));//
- String line = "";
- while((line = br.readLine()) != null){
- System.out.println(line);
- }
- }else{
- System.err.println("cannot readable");
- }
- } catch (IOException e) {
- System.err.println("error charset");
- }
-
- }
-
- }
复制代码 运行:
C:ex>java TestPath
2
-2
c:exaccess.log
path4: c:exaccess.log
--------------分割线---------------
aa
bb
cc
源码下载:http://file.javaxxz.com/2014/10/31/235809015.zip |
|