在Android中读取远程文本文件,可以使用HttpURLConnection或者第三方库如OkHttp或Retrofit。以下是使用HttpURLConnection的示例代码:
private String readTextFromUrl(String urlString) throws IOException {
InputStream inputStream = null;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
在AndroidManifest.xml中需要添加Internet权限:
<uses-permission android:name="android.permission.INTERNET" />
在主线程中调用该方法,例如:
new Thread(new Runnable() {
@Override
public void run() {
try {
String text = readTextFromUrl("https://example.com/text.txt");
Log.d("Text", text);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
注意:在主线程中不要直接执行耗时操作,否则会导致UI卡顿。可以使用AsyncTask或者Handler等方式将耗时操作放在子线程中执行。
领取专属 10元无门槛券
手把手带您无忧上云