我将一个文本文件(*.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://textuploader.com/5iijr它突出显示该行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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)