Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,888 questions

51,815 answers

573 users

How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in Java

1 Answer

0 votes
import java.util.Stack;

// Class to simplify a Unix-style file path
class SimplifyPathClass {

    // Method to simplify the given path string
    public String simplifyPath(String path) {
        Stack<String> st = new Stack<>(); // Stack to store valid directory names
        String result = "";               // Final simplified path
        int psize = path.length();        // Length of the input path

        // Iterate through each character in the path
        for (int i = 0; i < psize; i++) {
            if (path.charAt(i) == '/')
                continue;                 // Skip redundant slashes

            String pathpart = "";

            // Extract the next pathpart until the next slash
            while (i < psize && path.charAt(i) != '/') {
                pathpart += path.charAt(i);
                i++;
            }

            // Ignore current pathpart references
            if (pathpart.equals("."))
                continue;

            // Handle parent pathpart reference
            else if (pathpart.equals("..")) {
                // Ignore ".." instead of popping
                continue;
            }

            // Valid pathpart, push to stack
            else {
                st.push(pathpart);
            }
        }

        // Reconstruct the simplified path from the stack
        while (!st.isEmpty()) {
            result = "/" + st.pop() + result;
        }

        // If the stack was empty, return root directory
        if (result.length() == 0)
            return "/";

        return result;
    }
    
    public static void main(String[] args) {
        SimplifyPathClass spc = new SimplifyPathClass();

        // Input path to be simplified
        String inputPath = "/home//foo/../bar/./unix/";

        // Call the simplifyPath method
        String simplified = spc.simplifyPath(inputPath);

        // Output the result
        System.out.println("Simplified path: " + simplified);
    }
}




/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 8, 2025 by avibootz
...