Java Path Normalize normalize(String path)

Here you can find the source of normalize(String path)

Description

Normalize path

Patch windows-type path with '\' into forward slashes, and collapse ".."

License

Open Source License

Parameter

Parameter Description
path Path that may use Windows '\' or ".."

Return

Path with only '/' and up-references resolved

Declaration

public static String normalize(String path) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

public class Main {
    /** Normalize path//from w  w w  . j  a va2s.c o m
     *
     *  <p>Patch windows-type path with '\' into
     *  forward slashes,
     *  and collapse ".." up references.
     *
     *  @param path Path that may use Windows '\' or ".."
     *  @return Path with only '/' and up-references resolved
     */
    public static String normalize(String path) {
        // Pattern: '\(?!\)', i.e. backslash _not_ followed by another one.
        // Each \ is doubled as \\ to get one '\' into the string,
        // then doubled once more to tell regex that we want a '\'
        path = path.replaceAll("\\\\(?!\\\\)", "/");
        // Collapse "something/../" into "something/"
        int up = path.indexOf("/../");
        while (up >= 0) {
            final int prev = path.lastIndexOf('/', up - 1);
            if (prev >= 0)
                path = path.substring(0, prev) + path.substring(up + 3);
            else
                break;
            up = path.indexOf("/../");
        }
        return path;
    }
}

Related

  1. normalize(final String pathname)
  2. normalize(String path)
  3. normalize(String path)
  4. normalize(String path)
  5. normalize(String path)
  6. normalize(String path)
  7. normalize(String path)
  8. normalize(String path)
  9. normalize(String path)