我刚开始使用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();
}
问题1:在Android Studio(v0.5.8)中放置我自己的属性文件的位置?
问题2:我如何访问它们?
默认情况下,资源文件夹放在src/main/assets
中,如果它不存在则创建它。
然后你可以使用以下内容访问该文件:
getBaseContext().getAssets().open("app.properties")
您可以找到有关Gradle Android项目结构here的更多信息。
在主文件夹中创建一个子文件夹并将其命名为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;
}
}
您可以在主文件夹中创建资产子文件夹,然后在其中插入.properties文件。
然后,创建一个类来打开并读取文件,例如:
public class PropertiesReader {
private Context context;
private Properties properties;
public PropertiesReader(Context context) {
this.context = context;
//creates a new object ‘Properties’
properties = new Properties();
public Properties getProperties(String FileName) {
try {
//access to the folder ‘assets’
AssetManager am = context.getAssets();
//opening the file
InputStream inputStream = am.open(FileName);
//loading of the properties
properties.load(inputStream);
}
catch (IOException e) {
Log.e("PropertiesReader",e.toString());
}
}
return properties;
}
}
有关更多信息,请参阅http://pillsfromtheweb.blogspot.it/2014/09/properties-file-in-android.html
public static String getProperty(String key, Context context) throws IOException {
try {
Properties properties = new Properties();
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open("config.properties");
properties.load(inputStream);
return properties.getProperty(key);
}catch (IOException e){
e.fillInStackTrace();
}
return null;
}
文件夹结构: