android从项目中打开一个.properties文件

时间:2011-05-17 08:58:32

标签: android properties constants

我在default.properties,AndroidManifest.xml旁边定义了一个名为my_config.properties的文件。我的问题是。如何在我班上打开这个文件?

如果我将它移到类包中,我可以使用下面的代码读取它:

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

但是在这种情况下,文件需要与我使用此片段的类在同一个包中。如果在我的问题开始时定义它,我怎么读它? 谢谢。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

您可以从.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

相关问题