2012-12-15 24 views
0

我想知道是否有更好的方法在屬性文件中指向PATH。請看下面的代碼:更好的方法來指向屬性文件中的文件夾和文件?

public class Properties 
{ 
    //MIKE 
    public final static String PATH_TO_FILE_A = "C:\\programmer_MIKE\fileA.txt"; 
    public final static String PATH_TO_FILE_B = "C:\\programmer_MIKE\fileB.txt"; 

    //BILL 
    //public final static String PATH_TO_FILE_A = "/Users/BILL/Desktop/fileA.txt"; 
    //public final static String PATH_TO_FILE_B = "/Users/BILL/Desktop/fileB.txt"; 
} 

當任何開發人員需要調用FILE_A他只是做:

File file = new File(Properties.PATH_TO_FILE_A); 

如果他註釋掉MIKE的PATH_TO_FILE_A這個工程確定爲比爾。

問:有沒有更好的設計?如果BILL承諾他的工作包括屬性文件 - 他會給MIKE帶來問題(不用擔心,稍後他會得到一杯咖啡拿鐵咖啡)。

  • 的文件是大(2-4GB),我們不希望把他們在我們的資源庫(SVN),有時也只是臨時文件夾中創建PDF,所以我們不希望把他們在「./docs」路徑中。

感謝任何指針!

回答

2

如果無論出於何種原因,您確實需要硬編碼路徑,那麼您可以將它們存儲在用戶名索引的某種地圖中。喜歡的東西:

public class Properties { 

    private static Map<String, DeveloperPaths> properties = create(); 

    private static Map<String, DeveloperPaths> create() { 

     Map<String, DeveloperPaths> properties = new HashMap<String, DeveloperPaths>(); 

     properties.put("mike", new DeveloperPaths(
       "C:\\programmer_MIKE\fileA.txt", 
       "C:\\programmer_MIKE\fileB.txt") 
       ); 

     properties.put("bill", new DeveloperPaths(
       "/Users/BILL/Desktop/fileA.txt", 
       "/Users/BILL/Desktop/fileB.txt") 
       ); 

     return properties; 
    } 

    public static File FileA() 
    { 
     String user = System.getProperty("user.name"); 
     return properties.get(user).fileA; 
    } 

    public static File FileB() 
    { 
     String user = System.getProperty("user.name"); 
     return properties.get(user).fileB; 
    } 

} 

class DeveloperPaths { 
    public File fileA; 
    public File fileB; 

    public DeveloperPaths(String pathA, String pathB) { 
     fileA = new File(pathA); 
     fileB = new File(pathB); 
    } 
} 

然後,訪問每個路徑中的代碼將是相同的,無論顯影劑的,例如:

File myFile = Properties.fileA(); 
+0

是的,很喜歡。會使用它。謝謝你的提示! – adhg

0

這樣的事情應該外部配置和/或通過參數,系統參數或環境變量傳入。另外,你可以使用DI/IoC,但是當沒有附加的行爲時,IMO配置值就足夠了。

有一個硬編碼的默認是好的,但其他東西不屬於代碼。

1

通常路徑是可配置的entites並且應該被存儲在屬性文件中。

屬性文件在java中支持構建,它使用Properties對象來存儲該信息。

您可以在啓動時讀取屬性文件,或者在您的應用程序的init(或類似)方法中讀取屬性文件中的proeprties。這將使你的配置變得動態,任何人都可以改變它。

您可以創建一個靜態方法,並調用它像啓動:

import java.io.IOException; 
import java.io.InputStream; 
import java.util.Properties; 


public class GetProperties { 
    public static Properties prop = new Properties(); 

    public static void init() { 

     InputStream inputStream = GetProperties.class.getClassLoader().getResourceAsStream("application.properties"); 
     try { 
      prop.load(inputStream); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     }  
    } 
} 
+0

感謝您的意見。實際上,我實施了@R坎貝爾提出的解決方案,它爲我解決了問題。我可能會在將來使用你的(因爲它來自一個文件)謝謝 – adhg

相關問題