2015-10-06 64 views
0

我有一個加載從創建的目錄中的文件並將其顯示在服務器上的Java /騾子應用如本地主機/ file.txt的使用屬性文件來設置目錄中加載文件

File dir = new File("C:\\folder"); 
     dir.mkdirs(); 
     File file1 = new File(dir, filePath); 

的filepath是從URL - 它採用參數http.request.path eg file.txt並讀取文件

是否有反正我可以將硬編碼的代碼位設置文件夾爲mule/java屬性文件,而不是硬編碼它?

回答

0

您可以將路徑放在屬性文件中,並使用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(); 
    } 
} 
} 
+0

是否有一種特定的方式來指定屬性文件中的路徑?目前有它在「路徑= C:\\文件夾」 – gio10245

+0

這很好。你試過了嗎? –

+0

是的,我不知道該怎麼改變目錄中的代碼 - 文件file1 =新文件(dir,filePath);因爲dir是硬編碼的。加載屬性文件中的代碼似乎很好,但我確定如何在我的代碼中使用它 – gio10245