我正在尝试读取在线存储在我的 Android Studio 应用程序中的文本文件。 我尝试了一些代码,这些代码似乎在应用程序打开后立即崩溃。这是我尝试过的代码:
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setAppCacheEnabled(false);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setEnableSmoothTransition(true);
CookieManager.getInstance().setAcceptCookie(true);
mWebView.clearCache(true);
try {
URL url = new URL("http://urlhere.co.uk/files/testFile.txt");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
String link = null;
while((line = br.readLine()) != null) {
link = line;
}
mWebView.loadUrl("file:///" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + link);
br.close();
} catch (MalformedURLException e) {
System.out.println();
} catch (IOException e) {
System.out.print("test test");
}
}
只是作为一点解释。该文本文件包含将被加载到 web View 中的 URL。对于我想做的事情,这是我认为最好的方法。
更新 我使用了 logcat 并得到了一些错误,我认为这些错误是由此引起的:
java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
有人对我的应用程序立即崩溃的原因有任何建议吗?
提前致谢
最佳答案
您需要在后台线程中访问网络。 AsyncTask
非常适合执行此操作并随后在 UI 线程上访问结果。像这样的事情:
try {
final URL url = new URL("http://urlhere.co.uk/files/testFile.txt");
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
try {
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(is));
String line;
if ((line = br.readLine()) != null) {
return line;
}
} finally {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String link) {
mWebView.loadUrl("file:///" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + link);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (MalformedURLException e) {
e.printStackTrace();
}
(此外,将 URLConnection
(或 HttpURLConnection
)与 http
一起使用。到 HttpsURLConnection
的转换可与 https
配合使用 - 但看起来您已经发现了这一点。)
关于java - 读取在线存储的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48665966/