Java file normalize()方法及示例
java.nio.file . Path的 normalize() 方法用于从当前路径中返回一个消除了所有冗余名称元素的路径。
这个方法的精确定义取决于实现,它得出的路径不包含多余的名称元素。在许多文件系统中,”. “和”. “是表示当前目录和父目录的特殊名称。在这些情况下,所有出现的”… “都被认为是多余的,如果一个”… “前面有一个非”… “的名字,那么这两个名字都被认为是多余的。
语法
Path normalize()
参数: 该方法不接受任何东西。它是一个少参数的方法。
返回值: 该方法返回结果路径,如果不包含多余的名称元素,则返回此路径;如果此路径没有根组件且所有名称元素都是多余的,则返回空路径。
以下程序说明了normalize()方法:
程序1 :
// Java program to demonstrate// java.nio.file.Path.normalize() method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create object of Path // In this example \\.. starts with non".." // element Path path = Paths.get("D:\\..\\..\\.\\p2\\core" + "\\cache\\binary"); // print actual path System.out.println("Actual Path : " + path); // normalize the path Path normalizedPath = path.normalize(); // print normalized path System.out.println("\nNormalized Path : " + normalizedPath); }}
输出:
程序2 :
// Java program to demonstrate// java.nio.file.Path.normalize() method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("\\.\\.\\core" + "\\file\\binary.java"); // print actual path System.out.println("Actual Path : " + path); // normalize the path Path normalizedPath = path.normalize(); // print normalized path System.out.println("\nNormalized Path : " + normalizedPath); }}输出:
参考文献: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#normalize()
