Max Koretskyi
Max Koretskyi

Reputation: 105439

specify path to a file inside java program

I have a program which requires path to a file. Currently, it's configured like this:

public class Main {

    private static final String ACOUSTIC_MODEL_PATH =
            "resource:/edu/cmu/sphinx/models/en-us/en-us";
    private static final String DICTIONARY_PATH =
            "resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict";

I have two questions:

  1. What is this resource:/path/goes/here format, spefically resource word?
  2. How do I specify path to a file on a disk?

I tried these options but file fails to be found:

private static final String DICTIONARY_PATH = "/d/cmudict-en-us.dict";
private static final String DICTIONARY_PATH = "file:/d/cmudict-en-us.dict";
private static final String DICTIONARY_PATH = "file://d/cmudict-en-us.dict";

Here is how supposedly the path is used (location is path here):

public static URL resourceToURL(String location) throws MalformedURLException {
    Matcher jarMatcher = jarPattern.matcher(location);
    if (jarMatcher.matches()) {
        String resourceName = jarMatcher.group(1);
        return ConfigurationManagerUtils.class.getResource(resourceName);
    } else {
        if (location.indexOf(':') == -1) {
            location = "file:" + location;
        }
        return new URL(location);
    }
}

Upvotes: 0

Views: 252

Answers (2)

Tagir Valeev
Tagir Valeev

Reputation: 100139

Seems that resources:/ is just an internal pattern which is used in your program (see jarPattern regular expression which should be declared somewhere in your program). It's not a common syntax of describing the URLs. But if this pattern does not match, the fallback implementation is to treat the string as the URL. Local file URLs are always started with file:/// followed by normal path where backslashes are replaced with forward slashes.

Try the following string, it's a valid URL:

"file:///d:/cmudict-en-us.dict"

Upvotes: 1

Lexicographical
Lexicographical

Reputation: 501

If you want to specify a path on a disk, you can use its absolute path like so:

String path = "C:\Folder\AnotherFolder\file.txt";

The problem with this, however, is that the '\' symbol can cause issues as java recognizes it as trying to mark an escape sequence like \n, \r, etc. To prevent this error, you can replace '\' with '\\' and the JVM will read it as a regular path. So instead of the code above, you can try this :

String path = "C:\\Folder\\AnotherFolder\\file.txt";

Upvotes: 0

Related Questions