您可以將路徑放在屬性文件中,並使用Java中的Properties
類來讀取它。 示例代碼:
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
prop.load(input);
}catch(IOException e){
//handle exception
}
更多details-- 你必須創建一個新的屬性文件,它僅僅是一個.properties擴展名的文件。我們稱之爲sample.properties。您可以放置值,這些值是鍵值對。這是你將如何把值有:
dirpath = /home/dextr/Documents/docs/
fileName = puzzle.txt
你,你將不得不放置特性在應用程序的根文件或者你將不得不提供以讀它的相對路徑。 然後,使用類似以下代碼的代碼讀取properties
對象中的值。根據您需要的值,您使用適當的密鑰。
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SoSample {
public static void main(String[] args) {
Properties properties = new Properties();
InputStream input = null;
try {
input = new FileInputStream("sample.properties");
properties.load(input);
String dirPath = (String)properties.get("dirpath");
System.out.println(dirPath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
是否有一種特定的方式來指定屬性文件中的路徑?目前有它在「路徑= C:\\文件夾」 – gio10245
這很好。你試過了嗎? –
是的,我不知道該怎麼改變目錄中的代碼 - 文件file1 =新文件(dir,filePath);因爲dir是硬編碼的。加載屬性文件中的代碼似乎很好,但我確定如何在我的代碼中使用它 – gio10245