[英]Android - How can I read a text file from a url?
我上傳了一個文本文件(* .txt)到服務器,現在我想讀取文本文件...
沒試好我試過這個例子。
ArrayList<String> urls=new ArrayList<String>(); //to read each line
TextView t; //to show the result
try {
// Create a URL for the desired page
URL url = new URL("mydomainname.de/test.txt"); //My text file location
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
t=(TextView)findViewById(R.id.TextView1);
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
t.setText(urls.get(0)); // My TextFile has 3 lines
應用程序正在關閉......它可以取決於域名嗎? 應該有IP嗎? 我發現while循環沒有被執行。 因為如果我將t.setText *放在while循環中則沒有錯誤,並且TextView為空。 LogCat錯誤: http : t.setText(urls.get(0));
它用t.setText(urls.get(0));
突出顯示該行t.setText(urls.get(0));
提前致謝 !!!
嘗試使用HTTPUrlConnection或OKHTTP請求獲取信息,請嘗試以下操作:
總是在后台線程中做任何類型的網絡,否則android將拋出NetworkOnMainThread異常
new Thread(new Runnable(){
public void run(){
ArrayList<String> urls=new ArrayList<String>(); //to read each line
//TextView t; //to show the result, please declare and find it inside onCreate()
try {
// Create a URL for the desired page
URL url = new URL("http://somevaliddomain.com/somevalidfile"); //My text file location
//First open the connection
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(60000); // timing out in a minute
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (Exception e) {
Log.d("MyTag",e.toString());
}
//since we are in background thread, to post results we have to go back to ui thread. do the following for that
Activity.this.runOnUiThread(new Runnable(){
public void run(){
t.setText(urls.get(0)); // My TextFile has 3 lines
}
});
}
}).start();
1-)為您的清單文件添加Internet權限。
2-)確保在單獨的線程中啟動代碼。
這是對我很有用的片段。
public List<String> getTextFromWeb(String urlString)
{
URLConnection feedUrl;
List<String> placeAddress = new ArrayList<>();
try
{
feedUrl = new URL(urlString).openConnection();
InputStream is = feedUrl.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) // read line by line
{
placeAddress.add(line); // add line to list
}
is.close(); // close input stream
return placeAddress; // return whatever you need
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
我們的讀者功能已准備就緒,讓我們通過另一個線程來調用它
new Thread(new Runnable()
{
public void run()
{
final List<String> addressList = getTextFromWeb("http://www.google.com/sometext.txt"); // format your URL
runOnUiThread(new Runnable()
{
@Override
public void run()
{
//update ui
}
});
}
}).start();
聲明一個字符串變量來保存文本:
public String txt;
聲明一種檢查連通性的方法:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
像這樣delare AsyncTask:
private class ReadFileTask extends AsyncTask<String,Integer,Void> {
protected Void doInBackground(String...params){
URL url;
try {
//create url object to point to the file location on internet
url = new URL(params[0]);
//make a request to server
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//get InputStream instance
InputStream is=con.getInputStream();
//create BufferedReader object
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line;
//read content of the file line by line
while((line=br.readLine())!=null){
txt+=line;
}
br.close();
}catch (Exception e) {
e.printStackTrace();
//close dialog if error occurs
}
return null;
}
現在使用所需的Url調用AsyncTask:
if(isNetworkConnected())
{
ReadFileTask tsk=new ReadFileTask ();
tsk.execute("http://mystite.com/test.txt");
}
並且不要忘記在Manifest中添加以下權限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
只需將其放入一個新線程並啟動它將工作的線程。
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
URL url = new URL("https://texts-8e2bd.firebaseapp.com/");//my app link change it
HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String line;
StringBuilder lin2 = new StringBuilder();
while ((line = br.readLine()) != null)
{
lin2.append(line);
}
Log.d("texts", "onClick: "+lin2);
} catch (IOException e)
{
Log.d("texts", "onClick: "+e.getLocalizedMessage());
e.printStackTrace();
}
}
}).start();
而已。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.