【发布时间】:2017-03-23 04:52:27
【问题描述】:
我创建了一个文件 在assets文件夹中,现在我想从java类中读取文件并将其传递给同一类中的另一个函数,但由于某种原因我无法使用getAssest()方法。请帮忙!
public void configuration()
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(Context context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
【问题讨论】:
-
你需要有 Context 才能 getAssets() 像 context.getAssets()
-
您可以使用 this.getAssets() ,我们需要 this/context 以便 android 系统知道您在哪里使用资产
-
您需要使用有关该类的特定上下文。如果它是非活动类,则将
Context context作为configuration(Context context)方法中的参数传递并用作InputStream is = context.getAssets().open("config.txt"); -
我可以在任何地方使用这个参数吗?这个 Context 上下文实际上是做什么的?
-
是的,你会的。