This is the code I tried:
FileWriter outFile = new FileWriter(getAssets().open("USCOUNTIES"),append);
But it gives this error while compiling: "The method getAssets() is undefined for the type class1"
What is the correct usage in this scenario?
This is the code I tried:
FileWriter outFile = new FileWriter(getAssets().open("USCOUNTIES"),append);
But it gives this error while compiling: "The method getAssets() is undefined for the type class1"
What is the correct usage in this scenario?
您不能写入资产。open()返回一个InputStream;你不能InputStream用 aFileWriter或其他任何东西写信给 an。这超出了您得到的错误(由尝试调用getAssets()不是 a 的东西引起的Context)。
该方法getAssets()是Context的一部分,您可以在上下文本身或其子类上调用它Activity。您应该在需要的地方传递上下文
public void doSomethingRelatedToFiles(Context ctx){
AssetManager am = ctx.getAssets();
...
}
getAssets() 方法在Context接口中定义。所以你遇到的错误意味着 class1 没有实现 Context 接口。
基本上,此方法可用于 Activity 和 Service 和 Resource 类。
因此,您需要将 Context 作为方法参数传递。做这样的事情:
public void myMethod(Context context){
...
FileWriter outFile = new FileWriter(context.getAssets().open("USCOUNTIES"),append);
...
}
并假设您是myMethod从活动中调用的,请执行以下操作:
class1Instance.myMethod(this);