core-libs-dev Digest, Vol 29, Issue 40

Paulo Levi i30817 at gmail.com
Wed Sep 16 16:03:17 UTC 2009


I'd like a way to produce a File that is known to be valid from a
existing File assumed to be valid and a String. The string would be
mangled if needed according to the file system (truncating too large
name, eliminating forbidden characters) per file system installed.

I currently use this, but it not optimal obviously. Also i recall the
exception if the filesystem invariants were transgressed was
mysterious.

    public static File getSafeFileSystemFile(File parent, String
child) throws IOException {

        if (parent.isDirectory() || parent.mkdirs()) {

            String parentPath = parent.getCanonicalPath();
            String childPath = whiteList.matcher(child).replaceAll(" ");

            //-1 is seperator
            int maxLen = 255 - parentPath.length() - 1;

            if (childPath.length() > maxLen) {
                int extensionSeparator = childPath.lastIndexOf('.');
                String extension = "";
                if (extensionSeparator != -1) {
                    extension =
childPath.substring(extensionSeparator, childPath.length());
                    maxLen -= extension.length();
                }

                int i = maxLen - 1;
                while (childPath.charAt(i) != ' ' && i > 0) {
                    i--;
                }

                while (childPath.charAt(i) == ' ' && i > 0) {
                    i--;
                }

                if (i == 0) {
                    childPath = childPath.substring(0, maxLen - 1);
                } else {
                    childPath = childPath.substring(0, i + 1);
                }

                return new File(parentPath + File.separator +
childPath + extension);
            }
            return new File(parent, childPath);
        } else {
            throw new IllegalArgumentException("The parent file path
given is not writable or the file not a directory");
        }
    }

Deleting a file is a chore now, since deleting a normal file and
deleting a directory, is somewhat different, and to delete  directory
we have to delete the containing files in a recursion. I'm sure that
in some filesytems this could be more efficient if done in the api.



More information about the core-libs-dev mailing list