How to convert a filepath to valid file path in Java 1.7
Asked Answered
G

3

5

Using Java 1.6 Filepath can be entered by user and then I apply various regular expressions to remove characters that are invalid for the platform (such as '?' is invalid on Windows), and check path length to ensure we end up with a valid filepath for the OS before trying to create the filepath.

But there are two problems:

  1. Its a pain working out what is valid or not for each platform.
  2. I'm making assumptions based on default filesystem for the platform, but of course an OSX system could be writing to a non-mac filesystem such a FAT32, in which case these checks will not be valid.

So I was hoping there would be a better way to do it with NIO2 in Java 7, but haven't found a solution yet, is there one ?

Gram answered 9/10, 2012 at 17:2 Comment(0)
W
5

Depending on your expected result (corrected String? Invalid character position? Exception?), this should give you an idea of what can be done:

import java.io.File;
import java.nio.file.InvalidPathException;
public class Test {
    public static final void main(final String[] args) {
        final String current = new File(".").toPath().toAbsolutePath().normalize().toFile().toString();
        Test.correctPath(current);
        Test.correctPath(current + "aValidExpression");
        Test.correctPath(current + "aValidExpression?;:-&é");
        Test.correctPath(current + "aValidExpr//ession?;:-&é");
        Test.correctPath(current + "aValidExpre\\ssion?;:-&é");
    }

    public static final String correctPath(final String path) {
        try {
            final String returnValue = new File(path).toPath().toAbsolutePath().normalize().toFile().toString();
            System.out.println(returnValue);
            return returnValue;
        } catch (final InvalidPathException e) {
            System.err.println(e.getMessage());
            final int errorIndex = e.getIndex();
            final String newPath = path.substring(0, errorIndex - 1) + path.substring(errorIndex + 1);
            return Test.correctPath(newPath);
        }
    }
}

I hope it helps.

Wahlstrom answered 5/12, 2012 at 9:59 Comment(2)
@NoBugs Indeed you don't. In fact it's a good example of why you should follow Java convention and name your classes in CamelCase as well, because at a glance it looks like you have an instance variable called test, rather than calling the static method.Maladapted
Thanks. The -1 at errorIndex - 1 is not needed.Raimondo
S
2

The key to your question is the phrase "remove characters that are invalid for the platform". The various String to Path conversion functions, such as get() and resolve(), will tell you whether the string was valid as a path, but the won't tell why it's invalid. One way of being invalid is to contain invalid characters. Another would be to have, say, too many slash characters together. Regardless, the library does not give any more information than this; it provides no facility to assist in validating user input in any way that would help a user fix an input error. This ought to be a standard practice, admittedly, but it's hardly a practice at all.

Upshot: You'll have to write such a validation library yourself if you want to have one. Upside: You certainly aren't the only person with such a problem.

Scyphus answered 30/11, 2012 at 15:48 Comment(0)
L
1

I guess you should look at Path.getPath

public static Path get(String first,
   String... more)

 getPath("/foo","bar","gus")-->/foo/bar/gus

Converts a path string, or a sequence of strings that when joined form a path string, to a Path. If more does not specify any elements then the value of the first parameter is the path string to convert. If more specifies one or more elements then each non-empty string, including first, is considered to be a sequence of name elements (see Path) and is joined to form a path string. The details as to how the Strings are joined is provider specific but typically they will be joined using the name-separator as the separator. For example, if the name separator is "/" and getPath("/foo","bar","gus") is invoked, then the path string "/foo/bar/gus" is converted to a Path. A Path representing an empty path is returned if first is the empty string and more does not contain any non-empty strings.

Liter answered 9/10, 2012 at 17:7 Comment(1)
But does that fix invalid chars, I think it just throws an InvalidPathException if the input is invalid. Unfortunately I only have access to a OSX machine at the moment and whilst I thought chars like >,<,* were actually invalid on OSX it appears not , just awkward to create if using unix shell.Gram

© 2022 - 2024 — McMap. All rights reserved.