Generate a Relative Path

Sometimes in an application you will have a “home” directory associated with the application, and then some files associated with that home directory. To have the files in an independent position relative to the root of the file system, you may want to use relative paths to the files rather than absolute or canonical paths. If your input specifies files in absolute form, you can use the following code to generate the relative path from a ‘home’ directory to a file, whether it resides under that directory or in some other place in the file system. Examples:

 home = "/a/b/c"file = "/a/b/c/d/e.txt"relative path = "d/e.txt"home = "/a/b/c"file = "/a/d/f/g.txt"relative path = "../../d/f/g.txt"--------------------------------------------------------------------------import java.io.*;import java.util.*;/** * this class provides functions used to generate a relative path * from two absolute paths * @author David M. Howard */public class RelativePath {	/**	 * break a path down into individual elements and add to a list.	 * example : if a path is /a/b/c/d.txt, the breakdown will be [d.txt,c,b,a]	 * @param f input file	 * @return a List collection with the individual elements of the path inreverse order	 */	private static List getPathList(File f) {		List l = new ArrayList();		File r;		try {			r = f.getCanonicalFile();			while(r != null) {				l.add(r.getName());				r = r.getParentFile();			}		}		catch (IOException e) {			e.printStackTrace();			l = null;		}		return l;	}	/**	 * figure out a string representing the relative path of	 * 'f' with respect to 'r'	 * @param r home path	 * @param f path of file	 */	private static String matchPathLists(List r,List f) {		int i;		int j;		String s;		// start at the beginning of the lists		// iterate while both lists are equal		s = "";		i = r.size()-1;		j = f.size()-1;		// first eliminate common root		while((i >= 0)&&(j >= 0)&&(r.get(i).equals(f.get(j)))) {			i--;			j--;		}		// for each remaining level in the home path, add a ..		for(;i>=0;i--) {			s += ".." + File.separator;		}		// for each level in the file path, add the path		for(;j>=1;j--) {			s += f.get(j) + File.separator;		}		// file name		s += f.get(j);		return s;	}	/**	 * get relative path of File 'f' with respect to 'home' directory	 * example : home = /a/b/c	 *           f    = /a/d/e/x.txt	 *           s = getRelativePath(home,f) = ../../d/e/x.txt	 * @param home base path, should be a directory, not a file, or it doesn'tmake sense	 * @param f file to generate path for	 * @return path from home to f as a string	 */	public static String getRelativePath(File home,File f){		File r;		List homelist;		List filelist;		String s;		homelist = getPathList(home);		filelist = getPathList(f);		s = matchPathLists(homelist,filelist);		return s;	}	/**       * test the function       */	public static void main(String args[]) {		if (args.length != 2) {			System.out.println("RelativePath  ");			return;		}		System.out.println("home = " + args[0]);		System.out.println("file = " + args[1]);		System.out.println("path = " + getRelativePath(new File(args[0]),newFile(args[1])));	}}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.