java.nio.file中的Paths类
|
创建Path实例 Path类接受String或URI作为参数。 获取路径信息 |
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:\home\joe\foo
path.getName(1)--joe
getName(0): home
getNameCount: 3
home\joe
getParent: C:\home\joe
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:\ex\access.log
path4: c:\ex\access.log
--------------分割线---------------
aa
bb
cc

浙公网安备 33010602011771号