Code Snippets : Java : Absolute Path of File
current dir :
/home/sujee/projects/X/test
if I do
File f = new File
("../simple.txt");System.out.println (f.getAbsolutePath ());The out put is
/home/sujee/projects/X/test/../simple.txtI actually want to see
/home/sujee/projects/X/simple.txtThis snippet does it.
public static String getAbsolutePath(File f)
{
if (f == null)
return null;
String a = File.pathSeparator;
String b = File.separator;
String c = f.getAbsolutePath();
StringTokenizer tok = new StringTokenizer(f.getAbsolutePath(),
File.separator);
ArrayList segments = new ArrayList();
while (tok.hasMoreTokens())
{
String s = tok.nextToken();
if (s.equals(".."))
segments.remove(segments.size() - 1); // remove last
else
segments.add(s);
}
StringBuffer buf = new StringBuffer();
for (Iterator i = segments.iterator(); i.hasNext();)
{
String seg = (String) i.next();
// don't start off with \ on windows. C: is right, not \C:
if ((buf.length() == 0) && File.separator.equals("\\"))
buf.append (seg);
else
buf.append(File.separator).append(seg);
}
return buf.toString();
}
|