Java Path Normalize normalizePath(String path)

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

Description

normalize Path

License

Open Source License

Declaration

public static String normalizePath(String path) 

Method Source Code

//package com.java2s;
/****************************************************************************
 * Copyright (c) 2008-2014 Matthew Ballance and others.
 * 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
 *
 * Contributors:/*from   ww  w  .java 2 s .  c o  m*/
 *     Matthew Ballance - initial implementation
 ****************************************************************************/

public class Main {
    public static String normalizePath(String path) {
        StringBuilder ret = new StringBuilder();

        int i = path.length() - 1;
        int end;
        int skipCnt = 0;

        // First, skip any trailing '/'
        while (i >= 0 && (path.charAt(i) == '/' || path.charAt(i) == '\\')) {
            i--;
        }

        while (i >= 0) {
            // scan backwards find the next path element
            end = ret.length();

            while (i >= 0 && path.charAt(i) != '/'
                    && path.charAt(i) != '\\') {
                ret.append(path.charAt(i));
                i--;
            }

            if (i != -1) {
                ret.append("/");
                i--;
            }

            if ((ret.length() - end) > 0) {
                String str = ret.substring(end, ret.length() - 1);
                if (str.equals("..")) {
                    skipCnt++;
                    // remove .. element
                    ret.setLength(end);
                } else if (skipCnt > 0) {
                    ret.setLength(end);
                    skipCnt--;
                }
            }
        }

        return ret.reverse().toString();
    }
}

Related

  1. normalizePath(String fileSystemPath)
  2. normalizePath(String path)
  3. normalizePath(String path)
  4. normalizePath(String path)
  5. normalizePath(String path)
  6. normalizePath(String path)
  7. normalizePath(String path)
  8. normalizePath(String path)
  9. normalizePath(String path)