Java Path Normalize normalizePath(String filepath)

Here you can find the source of normalizePath(String filepath)

Description

Normalizes a file path by replacing various special path tokens (., .., etc.) with their canonical equivalents.

License

Open Source License

Parameter

Parameter Description
filepath The file path to normalize.

Return

The normalized file path.

Declaration

public static String normalizePath(String filepath) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from  w ww  . jav  a2  s .co m*/
     * Normalizes a file path by replacing various special
     * path tokens (., .., etc.) with their canonical equivalents.
     * @param filepath The file path to normalize.
     * @return The normalized file path.
     */
    public static String normalizePath(String filepath) {
        if (filepath.startsWith("./") || filepath.startsWith(".\\")) {
            filepath = filepath.substring(2);
        }
        filepath = filepath.replace("/./", "/");
        filepath = filepath.replace("\\.\\", "\\");
        int endPos = filepath.indexOf("/../");
        while (endPos != -1) {
            int startPos = endPos - 1;
            while (startPos >= 0 && '/' != filepath.charAt(startPos)) {
                startPos--;
            }
            if (startPos > 0) {
                filepath = filepath.substring(0, startPos) + "/" + filepath.substring(endPos + 4);
            } else {
                filepath = filepath.substring(endPos + 4);
            }
            endPos = filepath.indexOf("/../");
        }
        endPos = filepath.indexOf("\\..\\");
        while (endPos != -1) {
            int startPos = endPos - 1;
            while (startPos >= 0 && '\\' != filepath.charAt(startPos)) {
                startPos--;
            }
            if (startPos > 0) {
                filepath = filepath.substring(0, startPos) + "\\" + filepath.substring(endPos + 4);
            } else {
                filepath = filepath.substring(endPos + 4);
            }
            endPos = filepath.indexOf("\\..\\");
        }
        return filepath;
    }
}

Related

  1. normalizePath(final String path)
  2. normalizePath(final String path)
  3. normalizePath(final String... path)
  4. normalizePath(String _path, boolean _appendFinalSeparator)
  5. normalizePath(String absPath)
  6. normalizePath(String fileSystemPath)
  7. normalizePath(String path)
  8. normalizePath(String path)
  9. normalizePath(String path)