我的项目上有一个资产文件,该文件现在包含html代码,我想按波纹管代码上的字符串获取这些代码,所以请帮助我
我如何在波纹管代码上读取String中的资产文件
public class StartPage {
final String FILENAME = data();
private static final String HEAD_1 = "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "<head>"
+ "<meta content=\"en-us\" http-equiv=\"Content-Language\" />"
+ "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" />"
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\">"
+ "<title>";
@NonNull
public static File getStartPageFile(@NonNull Application application) {
return new File(application.getFilesDir(), FILENAME);
}
@NonNull private final String mTitle;
@Inject Application mApp;
@Inject SearchEngineProvider mSearchEngineProvider;
public StartPage() {
BrowserApp.getAppComponent().inject(this);
mTitle = mApp.getString(R.string.home);
}
@NonNull
public Single<String> getHomepage() {
return Single.create(new SingleAction<String>() {
@Override
public void onSubscribe(@NonNull SingleSubscriber<String> subscriber) {
StringBuilder homepageBuilder = new StringBuilder(HEAD_1 + mTitle );
BaseSearchEngine currentSearchEngine = mSearchEngineProvider.getCurrentSearchEngine();
String icon = currentSearchEngine.getIconUrl();
String searchUrl = currentSearchEngine.getQueryUrl();
homepageBuilder.append(icon);
homepageBuilder.append(searchUrl);
File homepage = getStartPageFile(mApp);
FileWriter hWriter = null;
try {
//noinspection IOResourceOpenedButNotSafelyClosed
hWriter = new FileWriter(homepage, false);
hWriter.write(homepageBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
Utils.close(hWriter);
}
subscriber.onItem(Constants.FILE + homepage);
}
});
private String data(){
InputStream inputStream = getAsseet().openRawResource(R.raw.database);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}
}
我在这里尝试读取资产文件,但是在这里给出错误(无法解析方法getAsset()),所以请通过编写代码来帮助我
谢谢
奥斯曼
最佳答案
getAssets()
是类Context
的方法。在活动中,您只能调用getAssets()
,因为它被视为this.getAssets()
,并且活动是Context
的子类。这就是为什么您可以在Activty
中调用它的原因。由于您的类不是Context
的子类,因此无法在类中调用getAssets()
或this.getAssets()
,因为没有此类方法。
因此,现在您必须获取一些Context
才能调用getAssets()
。您有一个Application mApp;
的实例,它是Context
以及Activty
的子类。这样您就可以拨打mApp.getAssets()