[英]specify path to a file inside java program
我有一個程序,它需要文件路徑。 當前,它的配置如下:
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";
我有兩個問題:
resource:/path/goes/here
是什么resource:/path/goes/here
格式,特別是resource
字? 我嘗試了這些選項,但找不到文件:
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";
這是假設使用路徑的方式(位置是此處的路徑):
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);
}
}
似乎resources:/
只是程序中使用的內部模式(請參閱jarPattern
正則表達式,應在程序中的某個位置聲明該正則表達式)。 描述網址不是一種常見的語法。 但是,如果此模式不匹配,則后備實現是將字符串視為URL。 本地文件URL始終以file:///
開頭,后跟普通路徑,其中反斜杠替換為正斜杠。
嘗試以下字符串,這是一個有效的URL:
"file:///d:/cmudict-en-us.dict"
如果要在磁盤上指定路徑,則可以使用其絕對路徑,如下所示:
String path = "C:\Folder\AnotherFolder\file.txt";
但是,與此相關的問題是,'\\'符號可能會引起問題,因為Java認為它試圖標記轉義序列,例如\\ n,\\ r等。為防止出現此錯誤,可以將'\\'替換為' \\\\',JVM將把它作為常規路徑讀取。 因此,您可以嘗試以下方法,而不是上面的代碼:
String path = "C:\\Folder\\AnotherFolder\\file.txt";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.