我上傳了一個文本文件(* .txt)到服務器,現在我想讀取文本文件...Android - 如何從網址讀取文本文件?
我試過這個例子沒有運氣。
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://textuploader.com/5iijr它突出顯示的行t.setText(urls.get(0));
在此先感謝!
「mydomainname.de/test.txt」不是一個有效的URL調用它。結果'URL'構造函數會拋出一個你完全忽略的'MalformedURLException'。作爲第二個結果,你的'urls'列表沒有被填充並保持爲空。 – Seelenvirtuose
我刪除了原始鏈接,這是有效的,我的列表沒有填充多少?我沒有明白。 @Seelenvirtuose – killertoge
你正在用一個空的列表初始化變量'urls'。然後你有一個try-catch塊,你首先用_malformed_URL創建一個URL對象。所以你會得到一個例外。這就讓你的變量'urls'保持不變。不多,不少。結論:不要吞下例外!至少打印堆棧跟蹤:'e.printStackTrace()'。 – Seelenvirtuose