Parsing File "roots" - break this code

I

Ian Pilcher

The java.io.File class doesn't provide a lot of help when parsing file
paths. In particular, it's difficult to determine whether a Windows
path starts with a filesystem identifier (a drive letter), a root
directory (a backslash), or both (c:\, \\, etc.).

Below is a quick program to test the algorithm that I've developed.
(Appologies in advance for any word wrap problems.) From what I can
tell it works as expected on Windows XP and Linux. I'd appreciate any
thoughts or testing, particularly if there's a Java platform that uses
file path semantics different from those of UNIX and Windows.

Note: In this scheme, root directories don't have names, nor does the
UNIX filesystem root. Windows filesystem roots are either a drive
letter followed by a colon (c: for example) or a single backslash.

Thanks!

import java.io.*;

class Foo
{
public static void main(String[] args)
{
File dirFile = new File(args[0]);

if (dirFile.getName().length() > 0)
{
processNormalDirectory(dirFile);
}
else
{
assert dirFile.getParent() == null;

if (dirFile.isAbsolute())
{
processRootAndDir(dirFile);
}
else
{
if (dirFile.getPath().endsWith(File.separator))
processRootDir(dirFile);
else
processFsRoot(dirFile);
}
}
}

static void processNormalDirectory(File dirFile)
{
System.out.println(dirFile.getPath() +
" represents a normal directory named " +
dirFile.getName());
}

static void processRootDir(File dirFile)
{
System.out.println(dirFile.getPath() + " represents a root
directory");
}

static void processFsRoot(File dirFile)
{
System.out.println(dirFile.getPath() +
" represents a filesystem root named " + dirFile.getPath());
}

static void processRootAndDir(File dirFile)
{
String rootName = dirFile.getPath();
rootName = rootName.substring(0,
rootName.length() - File.separator.length());

System.out.println(dirFile.getPath() +
" represents a filesystem root named " + rootName +
" and a root directory");
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top