android打开项目中的.properties文件

问题描述:

我在default.properties(AndroidManifest.xml)旁边定义了一个名为my_config.properties的文件。我的问题是。如何在我的课堂上打开这个文件?android打开项目中的.properties文件

,如果我将它移动到类包,我可以使用如下因素代码阅读:

Properties configFile = new Properties(); 
    try { 
     configFile.load(MyConstantsClass.class.getResourceAsStream("my_config.properties")); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

但在这种情况下,文件需要与类我用这个片段在同一封装内。当我的问题在开始时,我如何定义它? 谢谢。

您只能从Android中打开包含在APK中的文件,my_config.properties的当前位置不会包含在那里。我建议这种文件的正确位置是您的“资产”目录,您必须使用the correct class才能访问它。

+0

感谢。但有没有什么机会可以在构建时间内定义这样的东西。我不需要apk中的这些属性。我只需要根据产品/测试配置文件编译应用程序。例如,我将有一个常量定义为测试和错误作为产品。我需要这个,因为我为生产和测试服务器使用了不同的基础URL。有没有一种方法可以比使用if子句更好地处理这种事情,在发布之前手动检查代码以完成生产或.java类的所有更改? – DArkO 2011-05-17 11:33:04

+1

在这种情况下,如果你想知道你是否在生产或开发环境,那么你最好看看这个问题:http://stackoverflow.com/questions/1743683/distinguishing-development-mode-and-release -mode-environment-settings-on-android否则我不知道你会怎么做你想在Android上做什么。 – 2011-05-17 12:32:48

+0

好的谢谢你的一切。 – DArkO 2011-05-18 07:42:45

你能够获得价值从的.properties文件的例子是以下:

Properties prop = new Properties(); 
    String propertiesPath = this.getFilesDir().getPath().toString() + "/app.properties"; 

    try { 

     File existFile = new File(propertiesPath); 

     if(existFile.isFile()) 
     { 
      FileInputStream inputStream = new FileInputStream(propertiesPath); 
      prop.load(inputStream); 
      inputStream.close();  
     } 

    } catch (IOException e) { 
     System.err.println("Failed to open app.properties file"); 
     e.printStackTrace(); 
    } 

Aey.Sakon