简体   繁体   English

指定Java程序中文件的路径

[英]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? resource:/path/goes/here是什么resource:/path/goes/here格式,特别是resource字?
  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);
    }
}

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). 似乎resources:/只是程序中使用的内部模式(请参阅jarPattern正则表达式,应在程序中的某个位置声明该正则表达式)。 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. 但是,如果此模式不匹配,则后备实现是将字符串视为URL。 Local file URLs are always started with file:/// followed by normal path where backslashes are replaced with forward slashes. 本地文件URL始终以file:///开头,后跟普通路径,其中反斜杠替换为正斜杠。

Try the following string, it's a valid URL: 尝试以下字符串,这是一个有效的URL:

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

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. 但是,与此相关的问题是,'\\'符号可能会引起问题,因为Java认为它试图标记转义序列,例如\\ n,\\ r等。为防止出现此错误,可以将'\\'替换为' \\\\',JVM将把它作为常规路径读取。 So instead of the code above, you can try this : 因此,您可以尝试以下方法,而不是上面的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM