java.nio.file中的Paths類
阿新 • • 發佈:2019-01-31
建立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