有沒有一種方法可以使用一些函數來設置我的文件的位置(目錄)?在java中設置文件位置時沒有硬編碼
我每次使用硬編碼這樣
String folder = "/Users/...../Desktop/sample";
File dir = new File(folder);
File[] files = dir.listFiles();
文件位置是那裏有我能避免硬編碼任何方法?我正在使用的位置不是我當前的目錄。
建議或在這方面的幫助表示讚賞。 :)
有沒有一種方法可以使用一些函數來設置我的文件的位置(目錄)?在java中設置文件位置時沒有硬編碼
我每次使用硬編碼這樣
String folder = "/Users/...../Desktop/sample";
File dir = new File(folder);
File[] files = dir.listFiles();
文件位置是那裏有我能避免硬編碼任何方法?我正在使用的位置不是我當前的目錄。
建議或在這方面的幫助表示讚賞。 :)
當我看到它的一些比較簡單的方法是可行的,但可能不完全是你想要什麼:
導航從classpath
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL url = cl.getResource("relative/path/from/classpath");
或
String path = getClass().getClassLoader().getResource(".").getPath();
使用包含路徑條目的屬性文件
Properties properties = new Properties();
properties.load(new FileInputStream("filename.properties"));
properties.getProperty("PATH")
凡在你的屬性文件中,可以有一個像
PATH = the/absolute/path
線使用環境換貨變量
System.getenv("THE_PATH_ENV")
在那裏你將存儲在環境變量的路徑(如適用於您的操作系統)。
給出的路徑作爲參數 嗯,這是一個非常簡單的...只是訪問主字符串數組...
public static void main(String[] args){
String path = args[0]; //Or at whatever position it is in your parameter list
..
或者我能想到的可以使用Java文件系統命令手動遍歷目錄結構並在其中搜索某些內容。然而,我不會建議這樣做,因爲這不是他們所做的。如果有的話,我想我會回到一些第三方API。
How can I get relative path of the folders in my android project?
將在項目層次的文件夾,獲得相對路徑的項目,追加/硬編碼文件夾名稱和文件名。您只會在最後硬編碼文件名或上次文件夾名稱。
用戶屬性文件,並定義有
文件所在位置,您可以通過一個InputStream的屬性,所以你的文件幾乎可以在任何地方,並叫什麼。
Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
...
}
迭代爲:
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
首先,你可以創建一個屬性文件,路徑存儲在哪裏(你可以一次運行這個並使用該文件後來與您PROGRAMM):
/* Create/save properties once */
Properties prop = new Properties();
prop.setProperty("filePath", "/myPath/");
FileOutputStream fos = new FileOutputStream("sampleprops.xml");
prop.storeToXML(fos, "File configuration");
fos.close();
其次,你可以加載在那裏你想要的屬性您的代碼:
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("sampleprops.xml");
prop.loadFromXML(fis);
File dir = new File(prop.getProperty("filePath"));
File[] files = dir.listFiles();
你一定要確保,你有機會獲得sampleprops.xml文件(應該在你的應用程序的classpath)。通過這種方式,您可以配置要從外部配置文件使用的路徑。
你可以使用屬性文件或參數...是所有? – vainolo
http://stackoverflow.com/questions/2698002/how-can-i-get-relative-path-of-the-folders-in-my-project-java – Zohaib
@vainolo再次屬性文件我會硬編碼目錄是嗎?我的問題是,有沒有一種方法可以取代硬編碼? –