Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a filepath to valid file path in Java 1.7

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 ?

like image 911
Paul Taylor Avatar asked Oct 09 '12 17:10

Paul Taylor


3 Answers

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.

like image 152
ncenerar Avatar answered Oct 27 '22 02:10

ncenerar


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.

like image 41
eh9 Avatar answered Oct 27 '22 03:10

eh9


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.

like image 22
Amit Deshpande Avatar answered Oct 27 '22 01:10

Amit Deshpande