将自己的属性文件放在用Android Studio创建的android项目中的哪里?

bak*_*a83 13 android android-studio

我刚开始使用Android Studio.我不知道在哪里放置我自己的属性文件,因为项目结构中没有assets文件夹.

已发布的代码段在eclipse中工作正常,但在Android Studio中却没有.

码:

    Properties prop = new Properties();

    try {
        //load a properties file
        prop.load(new FileInputStream("app.properties"));

        //get the property value and print it out
        System.out.println(prop.getProperty("server_address"));

    } catch (IOException ex) {
        ex.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

问题1: 在Android Studio(v0.5.8)中放置我自己的属性文件的位置?

问题2: 我如何访问它们?

Sal*_*lem 12

默认情况下,资源文件夹放在其中src/main/assets,如果不存在则创建它.

然后你可以使用以下内容访问该文件:

getBaseContext().getAssets().open("app.properties")
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到有关Gradle Android项目结构的更多信息.


Pra*_*t_M 7

在主文件夹中创建一个子文件夹并将其命名为assets.将所有.properties文件放在此(assets)文件夹中.

SRC-> main->资产 - > mydetails.properties

您可以使用AssetManager类访问它

public class MainActivity extends ActionBarActivity {

TextView textView;
private PropertyReader propertyReader;
private Context context;
private Properties properties;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context=this;
    propertyReader = new PropertyReader(context);
    properties = propertyReader.getMyProperties("mydetails.properties");
    textView = (TextView)findViewById(R.id.text);
    textView.setText(properties.getProperty("Name"));
    Toast.makeText(context, properties.getProperty("Designation"), Toast.LENGTH_LONG).show();
    }
}


public class PropertyReader {

private Context context;
private Properties properties;

public PropertyReader(Context context){
    this.context=context;
    properties = new Properties();
}

public Properties getMyProperties(String file){
    try{
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = assetManager.open(file);
        properties.load(inputStream);

    }catch (Exception e){
        System.out.print(e.getMessage());
    }

    return properties;
    }
}
Run Code Online (Sandbox Code Playgroud)