jdk 1.7系列 (二)檔案 I/O 的基石 :Path

來源:互聯網
上載者:User

標籤:static   資訊   imp   基本用法   filename   掌握   normal   提取   ring   

在NIO.2的檔案 I/O 中,Path是必須掌握的關鍵類之一。Path通常代表檔案系統中的位置,比如 C:\Windows\System32 

 

什麼是根目錄、絕對路徑和相對路徑

比如說,代碼要讀取位於 /java7dev/src/main/Demo.java目錄下的檔案名稱。

  • 根路徑為 /java7dev
  • 絕對路徑為 /java7dev/src/main/
  • 進入到 絕對路徑下 可使用相對路徑 ../main

備忘:這裡簡略概括,想深入瞭解可訪問  https://www.cnblogs.com/crizygo/p/5369081.html

檔案 I/O 的關鍵基礎類
說明
Path Path類中的方法可以用來擷取路徑資訊,訪問該路徑中的各元素,將路徑轉換為其他形式,或提取路徑中的一部分。有的方法還可以匹配路徑字串以及移除路徑中的冗餘項
Paths 工具類,提供返迴路徑的輔助方法,比如get(String first, String ... more) 和 get(URI url)
FileSystem 與檔案系統互動的類,無論是預設的檔案系統,還是通過其同意資源標識(URI) 擷取的可選檔案系統
FileSystems 工具類,提供各種方法,比如其中用於返回預設檔案系統的FileSystems.getDefault()

 

備忘:Path不一定代表真實的檔案或者目錄。可隨心所欲地操作Path,用Files中的功能來檢查檔案是否存在,並對它進行處理。

 

Path的基本用法
package com.gudongcheng.jdk7.nio;import java.io.File;import java.nio.file.Path;import java.nio.file.Paths;/** * @author lizuoyang * @date 2018/10/30 * @desc Path類的用法 */public class PathDemo {    public static void main(String[] args) {        //建立絕對路徑        Path demo = Paths.get("/usr/bin/zip");        //擷取檔案名稱        System.out.println("File Name :" + demo.getFileName());        //擷取名稱元素的數量        System.out.println("Number of Name Elements:" + demo.getNameCount());        //擷取root路徑(頂層)        System.out.println("Root of Path:" + demo.getRoot());        //擷取0-2位子路徑        System.out.println("Subpath from Root, 2 elements deep:" + demo.subpath(0, 2));        //去除冗餘路徑 擷取檔案的真正位置        Path normalizedPath = Paths.get("./PathDemo.java").normalize();        System.out.println("Path normalizedPath:" + normalizedPath);        //合并兩個Path 通過resolve()        Path prefix = Paths.get("/uat");        Path completePath = prefix.resolve("conf/application.properties");        System.out.println("Path resolve :" + completePath.toAbsolutePath());        //File類和Path類的相互轉換        File file = new File("../demo.java");        //File to Path        Path file2Path = file.toPath();        System.out.println("File to Path:" + file2Path.toAbsolutePath());        //Path to File        File path2File = file2Path.toFile();        System.out.println("Path to File:" + path2File.getPath());    }}

jdk 1.7系列 (二)檔案 I/O 的基石 :Path

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.