Replaces the final component in the supplied path with the specified new component. - Java File Path IO

Java examples for File Path IO:Path

Description

Replaces the final component in the supplied path with the specified new component.

Demo Code

// Copyright (C) 2001-2012 Michael Bayne, et al.
//package com.java2s;

public class Main {
    /**//  w w w  .  ja  va 2 s  .c o  m
     * Replaces the final component in the supplied path with the
     * specified new component. For example, if <code>/foo/bar/baz</code>
     * was provided as the source path, <code>baz</code> would be replaced
     * with the supplied new path component. If no slashes occur in the
     * path, the entire path will be replaced. Note that this function is
     * intended for use on URLs rather than filesystem paths and thus
     * always uses forward slash rather than the platform defined path
     * separator.
     */
    public static String replaceFinalComponent(String source,
            String newComponent) {
        int sidx = source.lastIndexOf("/");
        if (sidx != -1) {
            return source.substring(0, sidx + 1) + newComponent;
        } else {
            return newComponent;
        }
    }
}

Related Tutorials